php - 从动态 MySql 表中的第 n 行开始获取 m 行

标签 php mysql database

场景是列出用户和他的 friend 上传的照片,按上传日期时间排序。我有一个 MySql 表照片,它是动态的,包含所有用户上传的照片。

最初我通过以下查询获得 10 行数据。当我得到接下来的 10 行时,用户将上传更多照片。那么如何从我之前已经得到的行开始选择接下来的 10 行呢?

select * from photo p where p.handle in (select handle from friends where user = '$handle') or p.handle='$handle' order by uldatetime desc limit ".$start.", 10;

最佳答案

你一定有一些 Auto increment primary key在你的数据库中。并说您正在以相反的顺序获取记录。假设开始显示结果时有 50 条记录

  1. 你获取了从 50 到 41 的记录
  2. 同时又插入了 5 条记录,因此您的最后一个 ID 从 50 增加到 55
  3. 现在不显示最后 20 条记录,而是获取主键 < 41 的最后 10 条记录,因此无论同时插入的记录如何,它都会给你 40 到 31

因此您的查询将更新为

select * from photo p where p.handle in (select handle from friends where user = '$handle') or p.handle='$handle' AND photo.[primarykey of photo table] < [last photo id displayed till now] order by uldatetime desc limit 0, 10;

替换[last photo id displayed till now][primarykey of photo table]具有相应的变量和字段。

关于php - 从动态 MySql 表中的第 n 行开始获取 m 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33009736/

相关文章:

php - laravel 5.4 输入日期时出错

mysql - MYSQL 使用哪个数据库 UI?我是网络开发新手

php - 对文本输入求和,其中输入数量根据 for 循环而变化

PHP 数组重复值

php - 来自另一个数据库的 MySQL 子查询,其中表名取决于主查询

sql - 规范化一对一 bool 关系

mysql - 如何从现有数据库导入到 opencart 数据库

database - 我们应该如何使用微服务构建我们的模型?

php - Laravel 5.5 发送数据查看而不重新加载页面

php - mySQL - 不要将相同的数据插入表中的行(如果存在)