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

mysqlmysqli database

要从 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)

相关文章