从 MySQL 中已排序列表的中间选择结果?
要从已排序列表的中间选择结果,需要结合使用 ORDER BY 子句和 LIMIT 子句。
让我们首先创建一个表。以下是查询 −
mysql> create table sortedListDemo -> ( -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> StudentName varchar(100) -> ); Query OK, 0 rows affected (0.46 sec)
以下是使用 insert 命令向表中插入一些记录的查询 −
mysql> insert into sortedListDemo(StudentName) values('John'); Query OK, 1 row affected (0.62 sec) mysql> insert into sortedListDemo(StudentName) values('Sam'); Query OK, 1 row affected (0.18 sec) mysql> insert into sortedListDemo(StudentName) values('Adam'); Query OK, 1 row affected (0.13 sec) mysql> insert into sortedListDemo(StudentName) values('James'); Query OK, 1 row affected (0.21 sec) mysql> insert into sortedListDemo(StudentName) values('Jace'); Query OK, 1 row affected (0.13 sec) mysql> insert into sortedListDemo(StudentName) values('Mike'); Query OK, 1 row affected (0.12 sec) mysql> insert into sortedListDemo(StudentName) values('Carol'); Query OK, 1 row affected (0.18 sec) mysql> insert into sortedListDemo(StudentName) values('Bob'); Query OK, 1 row affected (0.17 sec) mysql> insert into sortedListDemo(StudentName) values('Ramit'); Query OK, 1 row affected (0.16 sec) mysql> insert into sortedListDemo(StudentName) values('Chris'); Query OK, 1 row affected (0.21 sec) mysql> insert into sortedListDemo(StudentName) values('Robert'); Query OK, 1 row affected (0.14 sec) mysql> insert into sortedListDemo(StudentName) values('David'); Query OK, 1 row affected (0.21 sec)
以下是使用 select 语句从表中显示所有记录的查询 −
mysql> select * from sortedListDemo;
由此产生的输出如下 −
+----+-------------+ | Id | StudentName | +----+-------------+ | 1 | John | | 2 | Sam | | 3 | Adam | | 4 | James | | 5 | Jace | | 6 | Mike | | 7 | Carol | | 8 | Bob | | 9 | Ramit | | 10 | Chris | | 11 | Robert | | 12 | David | +----+-------------+ 12 rows in set (0.00 sec)
以下是从已排序列表的中间选择结果的查询。我们设置 LIMIT 为 4, 6,这意味着将随机显示 6 条记录 −
mysql> select *from sortedListDemo -> order by StudentName -> LIMIT 4,6;
由此产生的输出如下 −
+----+-------------+ | Id | StudentName | +----+-------------+ | 12 | David | | 5 | Jace | | 4 | James | | 1 | John | | 6 | Mike | | 9 | Ramit | +----+-------------+ 6 rows in set (0.00 sec)
广告