如何从MySQL查询返回第n条记录?
要从MySQL查询中获取第n条记录,可以使用LIMIT。语法如下-
select *from yourTableName order by yourColumnName limit n,1;
为了理解上述语法,让我们创建一个表。以下是创建表的查询-
mysql> create table NthRecordDemo −> ( −> Id int, −> Name varchar(200) −> );
使用以下查询在表中插入一些记录-
mysql> insert into NthRecordDemo values(100,'John'); mysql> insert into NthRecordDemo values(101,'Bob'); mysql> insert into NthRecordDemo values(102,'Carol'); mysql> insert into NthRecordDemo values(103,'Smith'); mysql> insert into NthRecordDemo values(104,'Johnson'); mysql> insert into NthRecordDemo values(105,'Sam'); mysql> insert into NthRecordDemo values(106,'David');
在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)