首页 > 代码库 > MySQL limit offset语法

MySQL limit offset语法

MySQL支持limit和offset的语法。本文主要用于备忘

闲话少叙,我们建立一张实验用的表:

mysql> create table limit_offset(    ->  id int auto_increment primary key,    ->  name varchar(20)    -> );Query OK, 0 rows affected (0.01 sec)

插入数据:insert into limit_offset(name) value(val),我们插入20条数据

mysql> select * from limit_offset;+----+--------+| id | name   |+----+--------+|  1 | name1  ||  2 | name2  ||  3 | name3  ||  4 | name4  ||  5 | name5  ||  6 | name6  ||  7 | name7  ||  8 | name8  ||  9 | name9  || 10 | name10 || 11 | name11 || 12 | name12 || 13 | name13 || 14 | name14 || 15 | name15 || 16 | name16 || 17 | name17 || 18 | name18 || 19 | name19 || 20 | name20 |+----+--------+20 rows in set (0.00 sec)

 

用法一:limit m。该语法是选择ResultSet中的前m条,包括m

mysql> select * from limit_offset limit 6;+----+-------+| id | name  |+----+-------+|  1 | name1 ||  2 | name2 ||  3 | name3 ||  4 | name4 ||  5 | name5 ||  6 | name6 |+----+-------+6 rows in set (0.00 sec)

 

用法二:limit m,n。该语法是选择从ResultSet中的第m条记录开始向后选择n条记录,不包括m

mysql> select * from limit_offset limit 10,6;+----+--------+| id | name   |+----+--------+| 11 | name11 || 12 | name12 || 13 | name13 || 14 | name14 || 15 | name15 || 16 | name16 |+----+--------+6 rows in set (0.00 sec)

 

用法三:limit m offset n。表示从第n条记录开始向后选择m条记录,不包括n(跟limit n,m)等价

mysql> select * from limit_offset limit 6 offset 10;+----+--------+| id | name   |+----+--------+| 11 | name11 || 12 | name12 || 13 | name13 || 14 | name14 || 15 | name15 || 16 | name16 |+----+--------+6 rows in set (0.00 sec)

MySQL limit offset语法