英文:
Stuck with union
问题
4 - 5 - 7 - 8
英文:
I like to select 2 rows before and 2 rows after the selected row sorted by ID.
ID:1 - 2 - 3 - 4 - 5 - 6 - 8 - 9 - 10
Suppose $skip is 6, this is what I like to achieve:
4 - 5 - 7 - 8
My code:
(SELECT * FROM $table WHERE id < $skip ORDER BY id DESC LIMIT 2) union all (SELECT * FROM $table WHERE id > $skip ORDER BY id ASC LIMIT 2)
This is what I get:
5 - 4 - 7 - 8
This didn't fixed it:
((SELECT * FROM $table WHERE id < $skip ORDER BY id DESC LIMIT 2) ORDER BY id ASC) union all (SELECT * FROM $table WHERE id > $skip ORDER BY id ASC LIMIT 2)
Testing this sorts correct, so I think the problem must be union all?
SELECT * FROM $table WHERE id < $skip ORDER BY id DESC LIMIT 2
Any ideas how to fix the first part?
答案1
得分: 0
在子查询中使用了 order by
,但你也应该在外部查询中添加一个:
(SELECT * FROM $table WHERE id < $skip ORDER BY id DESC LIMIT 2)
UNION ALL
(SELECT * FROM $table WHERE id > $skip ORDER BY id ASC LIMIT 2)
ORDER BY id;
或者,如果你使用的是 MySQL 8+,你可以使用窗口函数:
WITH base AS (
SELECT id,
LEAD(id) OVER (ORDER BY id) AS next_id,
LEAD(id, 2) OVER (ORDER BY id) AS next2_id,
LAG(id) OVER (ORDER BY id) AS prev_id,
LAG(id, 2) OVER (ORDER BY id) AS prev2_id
FROM $table
)
SELECT id FROM base WHERE $skip IN (next_id, next2_id, prev_id, prev2_id)
ORDER BY id;
英文:
You have order by
in the subqueries, but you should just add one to the outer query too:
(SELECT * FROM $table WHERE id < $skip ORDER BY id DESC LIMIT 2)
UNION ALL
(SELECT * FROM $table WHERE id > $skip ORDER BY id ASC LIMIT 2)
ORDER BY id;
Alternatively, you could use a window function (if you are on MySQL 8+):
WITH base AS (
SELECT id,
LEAD(id) OVER (ORDER BY id) AS next_id,
LEAD(id, 2) OVER (ORDER BY id) AS next2_id,
LAG(id) OVER (ORDER BY id) AS prev_id,
LAG(id, 2) OVER (ORDER BY id) AS prev2_id
FROM $table
)
SELECT id FROM base WHERE $skip IN (next_id, next2_id, prev_id, prev2_id)
ORDER BY id;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论