如何从 MySQL 查询中返回第 n 条记录?


要从 MySQL 查询结果中获取第 n 条记录,可以使用 LIMIT 语句。语法如下所示 −

select *from yourTableName order by yourColumnName limit n,1;

为了理解上述语法,让我们创建一个表。以下是用于创建表的查询 −

mysql> create table NthRecordDemo
   −> (
   −> Id int,
   −> Name varchar(200)
   −> );
Query OK, 0 rows affected (0.92 sec)

使用以下查询向表中插入一些记录 −

mysql> insert into NthRecordDemo values(100,'John');
Query OK, 1 row affected (0.09 sec)

mysql> insert into NthRecordDemo values(101,'Bob');
Query OK, 1 row affected (0.14 sec)

mysql> insert into NthRecordDemo values(102,'Carol');
Query OK, 1 row affected (0.22 sec)

mysql> insert into NthRecordDemo values(103,'Smith');
Query OK, 1 row affected (0.18 sec)

mysql> insert into NthRecordDemo values(104,'Johnson');
Query OK, 1 row affected (0.16 sec)

mysql> insert into NthRecordDemo values(105,'Sam');
Query OK, 1 row affected (0.16 sec)

mysql> insert into NthRecordDemo values(106,'David');
Query OK, 1 row affected (0.13 sec)

利用 select 语句显示表中所有记录。查询如下 −

mysql> select *from NthRecordDemo;

以下是输出 −

+------+---------+
| Id   | Name    |
+------+---------+
| 100  | John    |
| 101  | Bob     |
| 102  | Carol   |
| 103  | Smith   |
| 104  | Johnson |
| 105  | Sam     |
| 106  | David   |
+------+---------+
7 rows in set (0.00 sec)

使用以下查询从表中获取第 n 条记录 −

mysql> select *from NthRecordDemo order by Id limit 6,1;

以下是输出 −

+------+-------+
| Id   | Name  |
+------+-------+
| 106  | David |
+------+-------+
1 row in set (0.00 sec)

更新于: 30-Jul-2019

914 条浏览

开启你的职业生涯

完成课程,获得认证

立即开始
广告