【发布时间】:2013-03-26 09:43:52
【问题描述】:
我有一个名为 users 的简单表,其中包含以下数据:
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
谢谢
【问题讨论】:
-
你的表中的 7 在哪里?
-
对不起...这是一个错误:)
标签: php mysql sql database sorting