使用索引可以有效地选择前n行。让我们首先创建一个表-
create table DemoTable (StudentName varchar(100), StudentScore int );使用插入命令在表中插入一些记录-
insert into DemoTable values(John,34); insert into DemoTable values(Carol,55); insert into DemoTable values(Bob,58); insert into DemoTable values(Sam,38); insert into DemoTable values(Mike,48); insert into DemoTable values(Adam,41); insert into DemoTable values(Chris,47); insert into DemoTable values(Robert,40); insert into DemoTable values(David,89);使用select语句显示表中的所有记录-
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行的查询。我们使用了ORDERBY并跳过了5行。跳过后,有3条记录可见,因为我们使用了LIMIT3-
alter table DemoTable ADD INDEX name_score(StudentName,StudentScore); Records: 0 Duplicates: 0 Warnings: 0 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)