如何编写 MySQL 查询以选择前 10 条记录?
要选择前 10 条记录,我们可以首先按升序或降序对记录进行排序。在完成此操作后,使用 LIMIT 10 仅获取 10 条记录 -
select *from (select *from yourTableName ORDER BY yourColumnName ASC LIMIT 10)anyAliasName ORDER BY yourColumnName DESC;
让我们首先创建一个表 -
mysql> create table DemoTable683(Page int); Query OK, 0 rows affected (0.83 sec)
使用 insert 命令向表中插入一些记录——
mysql> insert into DemoTable683 values(100); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable683 values(101); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable683 values(102); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable683 values(103); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable683 values(104); Query OK, 1 row affected (0.20 sec) mysql> insert into DemoTable683 values(105); Query OK, 1 row affected (0.21 sec) mysql> insert into DemoTable683 values(106); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable683 values(107); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable683 values(108); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable683 values(109); Query OK, 1 row affected (0.28 sec) mysql> insert into DemoTable683 values(110); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable683 values(111); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable683 values(112); Query OK, 1 row affected (0.20 sec) mysql> insert into DemoTable683 values(113); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable683 values(114); Query OK, 1 row affected (0.10 sec)
使用 select 语句显示表中的所有记录 -
mysql> select *from DemoTable683;
将生成以下输出——
+------+ | Page | +------+ | 100 | | 101 | | 102 | | 103 | | 104 | | 105 | | 106 | | 107 | | 108 | | 109 | | 110 | | 111 | | 112 | | 113 | | 114 | +------+ 15 rows in set (0.00 sec)
以下是 MySQL 中选择前 10 条记录的查询 -
mysql> select *from (select *from DemoTable683 ORDER BY Page ASC LIMIT 10)tbl ORDER BY Page DESC;
将生成以下输出——
+------+ | Page | +------+ | 109 | | 108 | | 107 | | 106 | | 105 | | 104 | | 103 | | 102 | | 101 | | 100 | +------+ 10 rows in set (0.00 sec)
广告