我用来limit offset, num按页获取数据。但是页面之间的数据是交互的,这可以从主键course_id中看到。
limit offset, num
select version(); +---------------------+ | version() | +---------------------+ | 10.3.13-MariaDB-log | +---------------------+ show index from sc_base_course; +----------------+------------+-----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+ | Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment | +----------------+------------+-----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+ | sc_base_course | 0 | PRIMARY | 1 | course_id | A | 17 | NULL | NULL | | BTREE | | | | sc_base_course | 1 | agency_id | 1 | agency_id | A | 17 | NULL | NULL | | BTREE | | | | sc_base_course | 1 | agency_id | 2 | course_name | A | 17 | NULL | NULL | | BTREE | | | +----------------+------------+-----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
获取首页10行;
select course_id,grade_id from sc_base_course where agency_id = 10000 limit 0,10; +-----------+----------+ | course_id | grade_id | +-----------+----------+ | 13 | 1 | | 6 | 3 | | 12 | 4 | | 8 | 2 | | 7 | 2 | | 9 | 4 | | 16 | 1 | | 1 | 2 | | 17 | 1 | | 14 | 5 | +-----------+----------+
获取第二页的7行
select course_id,grade_id from sc_base_course where agency_id = 10000 limit 10,10; +-----------+----------+ | course_id | grade_id | +-----------+----------+ | 11 | 4 | | 12 | 4 | | 13 | 1 | | 14 | 5 | | 15 | 1 | | 16 | 1 | | 17 | 1 | +-----------+----------+
使用order by!
order by
SQL表表示无序的行集。如果没有order by子句,数据库可以自由按其喜欢的顺序返回行,并且在连续执行同一查询时结果可能不一致(因此,分页不稳定)。
select course_id, grade_id from sc_base_course where agency_id = 10000 order by course_id, grade_id limit 10,10;
请注意,不仅需要order by子句,而且此子句必须是 确定性的 。也就是说,子句中的列(或列集)必须唯一地标识每条记录- 否则,也将以未确定的顺序提取关系。