我有一个名为 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
谢谢