从 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)
广告