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

前端 未结 6 1729
暗喜
暗喜 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条回答
  •  遥遥无期
    2021-02-02 15:39

    Try this simple one (edited) -

    CREATE TABLE messages(
      id INT(11) DEFAULT NULL,
      message VARCHAR(255) DEFAULT NULL
    );
    
    INSERT INTO messages VALUES 
      (1, 'One tow three'),
      (2, 'No error in this'),
      (3, 'My testing message'),
      (4, 'php module test'),
      (5, 'hello world'),
      (6, 'team spirit'),
      (7, 'puzzle game'),
      (8, 'social game'),
      (9, 'stackoverflow'),
      (10, 'stackexchange');
    
    SET @text = 'hello world';
    
    SELECT id, message FROM (
      SELECT m.*, @n1:=@n1 + 1 num, @n2:=IF(message = @text, @n1, @n2) pos
        FROM messages m, (SELECT @n1:=0, @n2:=0) n ORDER BY m.id
    ) t
    WHERE @n2 >= num - 2 AND @n2 <= num + 2;
    
    +------+--------------------+
    | id   | message            |
    +------+--------------------+
    |    3 | My testing message |
    |    4 | php module test    |
    |    5 | hello world        |
    |    6 | team spirit        |
    |    7 | puzzle game        |
    +------+--------------------+
    

    N value can be specified as user variable; currently it is - '2'.

    This query works with row numbers, and this guarantees that the nearest records will be returned.

提交回复
热议问题