SELECT N rows before and after the row matching the condition?

前端 未结 6 1744
暗喜
暗喜 2021-02-02 15:02

The behaviour I want to replicate is like grep with -A and -B flags . eg grep -A 2 -B 2 \"hello\" myfile.txt will give me all the lines wh

6条回答
  •  猫巷女王i
    2021-02-02 15:47

    Don't know if this is at all valid MySQL but how about

    SELECT  t.* 
    FROM    theTable t
            INNER JOIN (
              SELECT id FROM theTable where message like '%hello%'
            ) id ON id.id <= t.id
    ORDER BY
            ID DESC
    LIMIT   3                    
    UNION ALL 
    SELECT  t.* 
    FROM    theTable t
            INNER JOIN (
              SELECT id FROM theTable where message like '%hello%'
            ) id ON id.id > t.id
    ORDER BY
            ID
    LIMIT   2
    

提交回复
热议问题