我想创建一个导航与下一步和上一步按钮,我想排序的流行的帖子。人气栏目由浏览量+点赞组成
Post_id | post_popularity
1 | 25
2 | 10
3 | 30
4 | 10
5 | 45因此,我尝试添加查询
//Previous
SELECT * FROM posts WHERE post_live=1 and post_popularity>$post_popularity ORDER BY post_popularity ASC LIMIT 1
//Next
SELECT * FROM posts WHERE post_live=1 and post_popularity<$post_popularity ORDER BY post_popularity DESC LIMIT 1这似乎循环了大多数帖子,然后我尝试
//Previous
SELECT * FROM posts WHERE post_live=1 and (post_popularity > $post_popularity) OR (post_popularity = $post_popularity AND post_id < $post_id) ASC LIMIT 1
//Next
SELECT * FROM posts WHERE post_live=1 and (post_popularity < $post_popularity) OR (post_popularity = $post_popularity AND post_id > $post_id) ASC LIMIT 1这似乎做了同样的事情。循环大多数帖子。关于如何存档此查询的任何指示。我非常适合你的帮助。
发布于 2017-04-26 17:07:18
我会用一个查询来选择当前、上一篇和下一篇文章。通过这种方式,您只需执行较少的查询即可加载显示一个站点所需的所有数据。
SELECT * FROM posts WHERE post_live=1 ORDER BY post_popularity ASC LIMIT 3 offset $index_of_current_post_minus_one;第一篇文章的$index_of_current_post_minus_one是0。你会得到3个结果,第一个是当前项,第二个是下一个,第三个可以忽略。如果你点击了下一步按钮,你的计数器$index_of_current_post_minus_one就会变成0 (所显示帖子的索引是1,但你总是减去1)。从现在开始,它变得直截了当。第一个结果行是你的前一行,第二行是你当前的,第三行是你的下一行。再次单击next,$index_of_current_post_minus_one将变为1,依此类推。
此外,您应该在表上创建一个索引,根据帖子的受欢迎程度对帖子进行预先排序,这样就不必对每个查询的行进行排序:
alter table post add index pop_live(post_popularity, post_live);https://stackoverflow.com/questions/39932157
复制相似问题