MySQL 中是否存在 SELECT TOP 命令来选择有限数量的记录?
mysqlmysqli database
MySQL 中没有 TOP 的概念。编写查询的另一种方法是使用 LIMIT,即选择 2 条记录,您需要使用 TOP 2。让我们看看 MySQL 中相同的语法
SELECT *FROM yourTableName ORDER BY yourColumnName DESC LIMIT 2;
为了理解上述语法,让我们创建一个表。创建表的查询如下
mysql> create table Top2Demo - > ( - > Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, - > Name varchar(20), - > Age int - > ); Query OK, 0 rows affected (0.91 sec)
使用 insert 命令在表中插入一些记录。
查询如下
mysql> insert into Top2Demo(Name,Age) values('Larry',23); Query OK, 1 row affected (0.13 sec) mysql> insert into Top2Demo(Name,Age) values('Bob',21); Query OK, 1 row affected (0.10 sec) mysql> insert into Top2Demo(Name,Age) values('Sam',19); Query OK, 1 row affected (0.14 sec) mysql> insert into Top2Demo(Name,Age) values('David',25); Query OK, 1 row affected (0.15 sec) mysql> insert into Top2Demo(Name,Age) values('Carol',22); Query OK, 1 row affected (0.39 sec)
使用 select 语句显示表中的所有记录。
查询如下
mysql> select *from Top2Demo;
以下是输出 −
+----+-------+------+ | Id | Name | Age | +----+-------+------+ | 1 | Larry | 23 | | 2 | Bob | 21 | | 3 | Sam | 19 | | 4 | David | 25 | | 5 | Carol | 22 | +----+-------+------+ 5 rows in set (0.00 sec)
以下是使用 LIMIT 2 选择前 2 条记录的查询
mysql> SELECT * FROM Top2Demo ORDER BY Age DESC LIMIT 2;
以下是输出 −
+----+-------+------+ | Id | Name | Age | +----+-------+------+ | 4 | David | 25 | | 1 | Larry | 23 | +----+-------+------+ 2 rows in set (0.00 sec)