大佬教程收集整理的这篇文章主要介绍了php-排序desc后mysql中的下一个和上一个记录,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
id | hops
1 | 3
2 | 1
3 | 5
4 | 2
5 | 6
6 | 5
我想根据跳的降序进行上一个/下一个导航.我使用以下查询来对降序进行排序:
SELECT * FROM users ORDER BY hops DESC, id DESC
结果如下:
id | hops
5 | 6
6 | 5
3 | 5
1 | 3
4 | 2
2 | 1
现在我想要的是,当我在mySQL查询中输入任何ID时,根据上述排序,我得到了上一个和下一个ID.例如:
对于id 5(在这种情况下,id = 5的跳数最高,因此之前没有任何记录):
id (current) | hops (current) | id (prev) | hops (prev) | id (next) | hops (next)
5 | 6 | NULL | NULL | 6 | 5
对于ID 6:
id (current) | hops (current) | id (prev) | hops (prev) | id (next) | hops (next)
6 | 5 | 5 | 6 | 3 | 5
对于ID 3:
id (current) | hops (current) | id (prev) | hops (prev) | id (next) | hops (next)
3 | 5 | 6 | 5 | 1 | 3
对于ID 1:
id (current) | hops (current) | id (prev) | hops (prev) | id (next) | hops (next)
1 | 3 | 3 | 5 | 4 | 2
对于ID 4:
id (current) | hops (current) | id (prev) | hops (prev) | id (next) | hops (next)
4 | 2 | 1 | 3 | 2 | 1
对于id 2(在这种情况下,id = 2的跳数最低,因此之后没有后续记录)
id (current) | hops (current) | id (prev) | hops (prev) | id (next) | hops (next)
2 | 1 | 4 | 2 | NULL | NULL
谢谢
解决方法:
尝试:
select cp.*, n.id id_next, n.hops hops_next
from
(select c.id id_current, c.hops hops_current, p.id id_prevIoUs, p.hops hops_prevIoUs
from
(select * from users where id = ?) c
left join users p on c.hops < p.hops or (c.id < p.id and c.hops = p.hops)
order by p.hops, p.id limit 1) cp
left join users n
on cp.hops_current > n.hops or (cp.id_current > n.id and cp.hops_current = n.hops)
order by n.hops desc, n.id desc limit 1
以上是大佬教程为你收集整理的php-排序desc后mysql中的下一个和上一个记录全部内容,希望文章能够帮你解决php-排序desc后mysql中的下一个和上一个记录所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。