如何从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)
阅读更多:MySQL 教程
极客教程