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

前端 未结 6 1730
暗喜
暗喜 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:58

    Adding an answer using date instead of an id. The use-case here is an on-call rotation table with one record pr week. Due to edits the id might be out of order for the purpose intended. Any use-case having several records pr week, pr date or other will of course have to be mended.

    +----------+--------------+------+-----+---------+----------------+
    | Field    | Type         | Null | Key | Default | Extra          |
    +----------+--------------+------+-----+---------+----------------+
    | id       | int(11)      | NO   | PRI | NULL    | auto_increment |
    | startdate| datetime     | NO   |     | NULL    |                |
    | person   | int(11)      | YES  | MUL | NULL    |                |
    +----------+--------------+------+-----+---------+----------------+
    

    The query:

    SELECT child.*
    FROM rota-table as child,
     (SELECT startdate
        FROM rota-table
        WHERE YEARWEEK(startdate, 3) = YEARWEEK(now(), 3) ) as parent
    WHERE
        YEARWEEK(child.startdate, 3) >= YEARWEEK(NOW() - INTERVAL 25 WEEK, 3)
        AND YEARWEEK(child.startdate, 3) <= YEARWEEK(NOW() + INTERVAL 25 WEEK, 3)
    

提交回复
热议问题