我有一张带照片的桌子
id | year| comm_count
0 2015 1
1 2016 2
2 2017 5
3 2018 7
4 2019 1
5 2020 9
6 2021 1
7 2022 1
我在所有照片中间的某处选择具有给定ID的照片。例如这样的
SELECT *
FROM photo
WHERE year > '2017'
ORDER BY comm_count DESC, year DESC
这会给我:
5,3,7,6,4
这给了我所有照片的清单。现在,我将此列表写在我的网络上,但用户可以单击某一张照片。之后,将打开详细页面。但是,从这个详细的页面上,我希望能够转到“下一个” M和“上一个” N张照片。这意味着,我需要根据当前选择的ID选择相邻的ID。该怎么办?
现在,我选择id = 7
,希望邻居成为:
prev: 5,3
和next: 6,4
。如何选择呢?
SqlFiddle-http://sqlfiddle.com/#!9/4f3f42/4/0
我无法在PHP中运行相同的查询并过滤结果,因为查询可能包含LIMITS(例如,对于LIMIT 2, 4
,我仍然需要正确的邻居)
答案 0 :(得分:2)
对于选定的ID为7的行,一旦有了year
和comm_count
的值,就可以进行两个简单的查询:
SELECT * FROM photo
WHERE year > 2017 AND (comm_count = 1 AND year <= 2022 OR comm_count < 1)
ORDER BY comm_count DESC, year DESC LIMIT 3 OFFSET 1
+----+------+------------+
| id | year | comm_count |
+----+------+------------+
| 6 | 2021 | 1 |
| 4 | 2019 | 1 |
+----+------+------------+
SELECT * FROM photo
WHERE year > 2017 AND (comm_count = 1 AND year >= 2022 OR comm_count > 1)
ORDER BY comm_count ASC, year ASC LIMIT 3 OFFSET 1;
+----+------+------------+
| id | year | comm_count |
+----+------+------------+
| 3 | 2018 | 7 |
| 5 | 2020 | 9 |
+----+------+------------+
如果使用MySQL 8.0,则可以使用LAG() and LEAD() functions。
SELECT id, year,
LAG(id, 1) OVER w AS next,
LAG(id, 2) OVER w AS next_next,
LEAD(id, 1) OVER w AS prev,
LEAD(id, 2) OVER w AS prev_prev
FROM photo
WHERE year > 2017
WINDOW w AS (ORDER BY comm_count DESC, year DESC)
+----+------+------+-----------+------+-----------+
| id | year | next | next_next | prev | prev_prev |
+----+------+------+-----------+------+-----------+
| 5 | 2020 | NULL | NULL | 3 | 7 |
| 3 | 2018 | 5 | NULL | 7 | 6 |
| 7 | 2022 | 3 | 5 | 6 | 4 |
| 6 | 2021 | 7 | 3 | 4 | NULL |
| 4 | 2019 | 6 | 7 | NULL | NULL |
+----+------+------+-----------+------+-----------+