SQL date intervals query

前端 未结 3 2014
無奈伤痛
無奈伤痛 2021-01-21 12:03

I am managing an event database. Every event has a start and end timestamp (INT, unix timestamp).

Currently i\'m able to do the following things with a sing

相关标签:
3条回答
  • 2021-01-21 12:12

    When you want to query all events "today" (or some other date), event those starting in the past or "today" and ending "today" or in the future you need some query like:

    SELECT * FROM `event` WHERE 
       (`start` >= :start) AND (`end` <= :end) OR
       (`start` <= :end) AND (`end` >= :start)
    ORDER BY start ASC
    

    with ? being your actual date.

    Test data:
    
    123456789
       nn     <-- :start, :end
     xx       1 
          xx  2 
      xx      3 s
        xx    4 s
      xxxx    5 s
       xx     6 s
    
    Test query:
    
    select * from event where 
    (start >= 4 and end <= 5) or
    (start <= 5 and end >= 4)
    
    0 讨论(0)
  • 2021-01-21 12:23

    If I get the question right, with [:start, :end] being your date range of interest, you're looking for:

    select *
     from event
    where -- event started earlier, ends later
          start <= :start and :start <= end
       or -- event starts during [:start, :end]
          :start <= start and start <= :end
       or -- event ends during [:start, :end]  
          :start <= end and end <= :end;
    

    If you're looking for a particular :day, use :day as :start and :day + 1 day as :end.

    0 讨论(0)
  • 2021-01-21 12:33

    I think you should modify query like this:

    SELECT * FROM `event` WHERE ? BETWEEN `start` AND `end` ORDER BY start ASC
    

    where param ? is the current date or current timestamp.

    0 讨论(0)
提交回复
热议问题