我的iPhone应用程序连接到我的PHP web服务从MySQL数据库中检索数据,一个请求可以返回500个结果。
实现分页和一次检索20个项的最佳方法是什么?
假设我从数据库中接收了前20个条目,我现在如何请求接下来的20个条目?
我的iPhone应用程序连接到我的PHP web服务从MySQL数据库中检索数据,一个请求可以返回500个结果。
实现分页和一次检索20个项的最佳方法是什么?
假设我从数据库中接收了前20个条目,我现在如何请求接下来的20个条目?
当前回答
如果您希望在存储过程中执行此操作,可以尝试此操作
SELECT * FROM tbl limit 0, 20.
不幸的是,使用公式不起作用,所以你可以执行一个准备好的语句,或者只是给过程的开始和结束值。
其他回答
为查询定义OFFSET。例如
Page 1-(记录01-10):offset = 0, limit=10;
第2页-(记录11-20)offset =10, limit =10;
并使用以下查询:
SELECT column FROM table LIMIT {someLimit} OFFSET {someOffset};
第2页示例:
SELECT column FROM table
LIMIT 10 OFFSET 10;
本教程展示了一种进行分页的好方法。 使用MySQL进行高效分页
简而言之,避免使用OFFSET或较大的LIMIT
如果您希望在存储过程中执行此操作,可以尝试此操作
SELECT * FROM tbl limit 0, 20.
不幸的是,使用公式不起作用,所以你可以执行一个准备好的语句,或者只是给过程的开始和结束值。
对于500条记录,效率可能不是问题,但如果你有数百万条记录,那么使用WHERE子句来选择下一页可能会更有利:
SELECT *
FROM yourtable
WHERE id > 234374
ORDER BY id
LIMIT 20
这里的“234374”是您查看的上一页中最后一条记录的id。
这将使id上的索引能够用于查找第一条记录。如果你使用LIMIT偏移量,20,你会发现它变得越来越慢,随着你的页面接近尾声。正如我所说的,如果只有200条记录,这可能无关紧要,但如果结果集更大,情况就不同了。
Another advantage of this approach is that if the data changes between the calls you won't miss records or get a repeated record. This is because adding or removing a row means that the offset of all the rows after it changes. In your case it's probably not important - I guess your pool of adverts doesn't change too often and anyway no-one would notice if they get the same ad twice in a row - but if you're looking for the "best way" then this is another thing to keep in mind when choosing which approach to use.
如果您确实希望使用带有偏移量的LIMIT(如果用户直接导航到页10000,而不是逐个分页,这是必要的),那么您可以阅读这篇关于晚期行查找的文章,以提高带有较大偏移量的LIMIT的性能。
下面是我如何使用node.js和MySQL数据库解决这个问题。 首先,让我们声明变量!
const
Key = payload.Key,
NumberToShowPerPage = payload.NumberToShowPerPage,
Offset = payload.PageNumber * NumberToShowPerPage;
NumberToShowPerPage是显而易见的,但是偏移量是页码。
现在SQL查询…
pool.query("SELECT * FROM TableName WHERE Key = ? ORDER BY CreatedDate DESC LIMIT ? OFFSET ?", [Key, NumberToShowPerPage, Offset], (err, rows, fields) => {}));
我将把它分解一下。
Pool, is a pool of MySQL connections. It comes from mysql node package module. You can create a connection pool using mysql.createPool. The ?s are replaced by the variables in the array [PageKey, NumberToShow, Offset] in sequential order. This is done to prevent SQL injection. See at the end were the () => {} is? That's an arrow function. Whatever you want to do with the data, put that logic between the braces. Key = ? is something I'm using to select a certain foreign key. You would likely remove that if you don't use foreign key constraints.
希望这能有所帮助。