Stuck with union

huangapple go评论59阅读模式
英文:

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 &lt; $skip ORDER BY id DESC LIMIT 2) 
UNION ALL 
(SELECT * FROM $table WHERE id &gt; $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;

huangapple
  • 本文由 发表于 2023年2月26日 23:04:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/75572869.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定