且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从 MySQL 数据库中选择分页明智的 N 条记录?

更新时间:2023-01-28 19:48:31

第一百

 SELECT * FROM <table_name> ORDER BY id ASC LIMIT 0, 100

下一百

 SELECT * FROM <table_name> ORDER BY id ASC LIMIT 100, 100

你对下单很细心

限制声明说明:LIMIT 语句不是 WHERE 子句.它不按 id 选择,实际上也不按任何条件选择,(where 子句可以做到这一点)相反,limit 子句只是确保您是返回作为一切"子集的结果的一部分 block.因此为什么每次都提到一个 order by 很重要,这样每个后续调用都会按顺序给你正确的数据块,你可以 'next', 'next', '接下来'通过他们

THE LIMIT STATEMENT EXPLAINED: The LIMIT statement is NOT a WHERE clause. It does not select by id nor in fact by any criteria, (there where clause does that) Instead the limit clause simply ensures that you are returned a piece of the block of results that are subset of "everything". Hence why it is important to mention an order by each time, so that each subsequent call will give you the correct piece of the data block in order, and you can 'next', 'next', 'next' through them

EG:对于无序表this_table:

+-------+-------------+
|  id   |   value     |
+-------+-------------+
|  1    |     bob     |
|  12   |     fish    |
|  112  |     pink    |
|  2    |     cat     |
|  8    |     dog     |
|  56   |     blue    |
|  88   |     grey    |
|  87   |     red     |
+-------+-------------+

选择返回如下:

SELECT * FROM <this_table> ORDER BY id ASC LIMIT 0,5
+-------+-------------+
|  id   |   value     |
+-------+-------------+
|  1    |     bob     |
|  2    |     cat     |
|  8    |     dog     |
|  12   |     fish    |
|  56   |     blue    |
+-------+-------------+

SELECT * FROM <this_table> ORDER BY id ASC LIMIT 5,5
+-------+-------------+
|  id   |   value     |
+-------+-------------+
|  87   |     red     |
|  88   |     grey    |
|  112  |     pink    |
+-------+-------------+

注意缺少第 9 行和第 10 行,这是故意的,显示 MySQL 按预期工作

notice the lack of rows 9 and 10 this is deliberate and shows MySQL working as intended

顺便说一句,您还应该考虑在 id 上添加索引,这将大大提高这些选择的速度

incidentally you should also look at adding an index on id this will MASSIVELY increase the speed of these selects

ALTER TABLE <table_name> ADD INDEX `id` (`id`)