使用非唯一值排序MySQL查询
我想用“下一步”和“上一步”按钮创建一个导航,并且我想按帖子的流行程度对顺序进行排序。“人气”栏由视图+喜欢组成使用非唯一值排序MySQL查询,mysql,Mysql,我想用“下一步”和“上一步”按钮创建一个导航,并且我想按帖子的流行程度对顺序进行排序。“人气”栏由视图+喜欢组成 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_popularit
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
//上一个
从post\u live=1和post\u popularity>$post\u popularity ORDER BY post\u popularity ASC LIMIT 1的帖子中选择*
//下一个
从post_live=1和post_popularity$post_popularity)或(post_popularity=$post_popularity和post_id<$post_id)ASC LIMIT 1的帖子中选择*
//下一个
从post_live=1和(post_popularity<$post_popularity)或(post_popularity=$post_popularity和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\u减去是0
。您将得到3个结果:第一个是当前项,第二个是下一个,第三个可以忽略。如果按“下一步”按钮,则递增计数器$index\u of\u current\u post\u减一
变为0
(显示的帖子的索引为1,但始终减1)。从现在起,它变得直截了当。第一个结果行是上一个结果行,第二个结果行是当前结果行,第三个结果行是下一个结果行。再次单击“下一步”,当前帖子的$index\u减去一个变为1
,依此类推
此外,您应该在表上创建一个索引,根据文章的受欢迎程度对其进行预排序,这样就不能为每个查询对行进行排序:
alter table post add index pop_live(post_popularity, post_live);
尝试使用//PreviousSELECT*FROM post\u live=1和post\u popularity>=$post\u popularity和post\u id!=$post_id ASC按post_流行度排序,post_id限制1
//下一步从post_live=1和post_流行度的帖子中选择*
alter table post add index pop_live(post_popularity, post_live);