從 MySQL 查詢中高效選擇前 n 行的方法?


使用索引高效選擇前 n 行。首先,讓我們建立一個表——

mysql> create table DemoTable (StudentName varchar(100), StudentScore int );
Query OK, 0 rows affected (0.66 sec)

示例

使用 insert 命令插入一些記錄到表中——

mysql> insert into DemoTable values('John',34);
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable values('Carol',55);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values('Bob',58);
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values('Sam',38);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('Mike',48);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values('Adam',41);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values('Chris',47);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values('Robert',40);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values('David',89);
Query OK, 1 row affected (0.18 sec)

使用 select 語句從表中顯示所有記錄——

mysql> select *from DemoTable;

輸出

+-------------+--------------+
| StudentName | StudentScore |
+-------------+--------------+
| John        | 34           |
| Carol       | 55           |
| Bob         | 58           |
| Sam         | 38           |
| Mike        | 48           |
| Adam        | 41           |
| Chris       | 47           |
| Robert      | 40           |
| David       | 89           |
+-------------+--------------+
9 rows in set (0.00 sec)

示例

以下是選擇前 n 行的高效查詢。我們使用了 ORDER BY 並在第 5 行前面加了省略號。在省略號之後,有 3 條可見記錄,因為我們使用了 LIMIT 3——

mysql> alter table DemoTable ADD INDEX name_score(StudentName,StudentScore);
Query OK, 0 rows affected (0.61 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> select StudentName,StudentScore from DemoTable order by StudentScore LIMIT 5,3;

輸出

+-------------+--------------+
| StudentName | StudentScore |
+-------------+--------------+
| Mike        | 48           |
| Carol       | 55           |
| Bob         | 58           |
+-------------+--------------+
3 rows in set (0.00 sec)

更新於:2020 年 7 月 2 日

356 次瀏覽

開啟你的 職業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.