gpt4 book ai didi

mysql - 使用非唯一值对 MySQL 查询进行排序

转载 作者:行者123 更新时间:2023-11-29 03:23:39 25 4
gpt4 key购买 nike

我想创建一个带有下一个和上一个按钮的导航,并且我想按帖子的受欢迎程度对顺序进行排序。人气栏目由浏览量+点赞数组成

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

这似乎做同样的事情。循环大多数帖子。有关如何存档此查询的任何指示。我非常感谢你的帮助。

最佳答案

我会通过一个查询来选择当前、上一篇和下一篇文章。这样一来,您只需执行更少的查询即可加载显示一个站点所需的所有数据。

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_one0。您会得到 3 个结果,第一个是当前项目,第二个是下一个,第三个可以忽略。如果你点击下一个按钮,你的计数器 $index_of_current_post_minus_one 会增加到 0(显示的帖子的索引是 1,但你总是减去 1)。从现在开始,它变得直截了当。第一个结果行是您的上一个,第二个是您当前的,第三个是您的下一个。再次单击下一步,$index_of_current_post_minus_one 变为 1,依此类推。

此外,你应该在你的表上创建一个索引,根据它们的受欢迎程度对你的帖子进行预先排序,这样就不必为每个查询对行进行排序:

alter table post add index pop_live(post_popularity, post_live);

关于mysql - 使用非唯一值对 MySQL 查询进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39932157/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com