我正在寻找一个带有last_id和order条件的MYSQL分页解决方案,使用LIMIT,OFFSET我需要找出last_id的偏移量。
例如,我有一个表新闻(id,title,updated_at),第一页返回3,1,2,5,4,第二页我有3个参数(last_id是4,order by updated_at desc ,limit是5),我需要通过updated_at desc。
找出id 4 order的偏移量+------+-------+---------------------+
| id | title | updated_at |
+------+-------+---------------------+
| 3 | test3 | 2018-01-22 11:30:08 |
+------+-------+---------------------+
| 1 | test1 | 2018-01-21 12:30:08 |
+------+-------+---------------------+
| 2 | test2 | 2018-01-20 12:30:08 |
+------+-------+---------------------+
| 5 | test5 | 2018-01-19 13:30:08 |
+------+-------+---------------------+
| 4 | test4 | 2018-01-18 14:30:08 |
+------+-------+---------------------+
....
+------+-------+---------------------+
| 11 | test11 | 2018-01-17 14:30:08 |
+------+-------+---------------------+
| 12 | test12 | 2018-01-16 15:30:08 |
+------+-------+---------------------+
我想要返回的第二页是11,12,....,有没有有效的方法来实现它?
答案 0 :(得分:0)
通过updated_at desc:
计算id 4顺序的偏移量SELECT @rownum:=@rownum + 1 AS offset, id, title, updated_at
FROM news, (SELECT @rownum:=0) AS r
ORDER BY updated_at DESC;
现在你得到特定行的偏移量。
然后你可以做类似的事情:
SELECT * FROM
(SELECT @rownum:=@rownum + 1 AS offset, id, title, updated_at
FROM news, (SELECT @rownum:=0) AS r ORDER BY updated_at DESC) AS t
WHERE offset > 5;
答案 1 :(得分:0)
使用SQL似乎效率不高,也许按代码订购新闻更为合适。