How can I select adjacent rows to an arbitrary row (in sql or postgresql)?

后端 未结 5 1841
猫巷女王i
猫巷女王i 2021-02-18 17:16

I want to select some rows based on certain criteria, and then take one entry from that set and the 5 rows before it and after it.

Now, I can do this numerically if ther

5条回答
  •  面向向阳花
    2021-02-18 17:35

    There's a lot of ways to do it if you run two queries with a programming language, but here's one way to do it in one SQL query:

    (SELECT * FROM table WHERE id >= 34 AND active = 1 ORDER BY id ASC LIMIT 6)
    UNION
    (SELECT * FROM table WHERE id < 34 AND active = 1 ORDER BY id DESC LIMIT 5)
    ORDER BY id ASC
    

    This would return the 5 rows above, the target row, and 5 rows below.

提交回复
热议问题