在 MySQL 中获取至少 x 行记录?
要获取至少 x 行的内容,你需要使用 LIMIT 子句。以下是语法 −
select *from yourTableName order by yourColumnName DESC limit yourXNumberOfRows;
我们先创建一个表 −
mysql> create table DemoTable ( EmployeeId int NOT NULL AUTO_INCREMENT PRIMARY KEY,EmployeeName varchar(100) ); Query OK, 0 rows affected (0.76 sec)
使用 insert 命令在表中插入一些记录 −
mysql> insert into DemoTable(EmployeeName) values('Chris'); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable(EmployeeName) values('David'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable(EmployeeName) values('Bob'); Query OK, 1 row affected (0.51 sec) mysql> insert into DemoTable(EmployeeName) values('Robert'); Query OK, 1 row affected (0.37 sec) mysql> insert into DemoTable(EmployeeName) values('Mike'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable(EmployeeName) values('Sam'); Query OK, 1 row affected (0.13 sec)
使用 select 语句显示表中的所有记录 −
mysql> select *from DemoTable;
这会产生以下输出 −
+------------+--------------+ | EmployeeId | EmployeeName | +------------+--------------+ | 1 | Chris | | 2 | David | | 3 | Bob | | 4 | Robert | | 5 | Mike | | 6 | Sam | +------------+--------------+ 6 rows in set (0.00 sec)
以下是获取 MySQL 中至少 x 行记录的查询。在这里,我们只显示 2 行 −
mysql> select *from DemoTable order by EmployeeName DESC limit 2;
这会产生以下输出 −
+------------+--------------+ | EmployeeId | EmployeeName | +------------+--------------+ | 6 | Sam | | 4 | Robert | +------------+--------------+ 2 rows in set (0.02 sec)
广告