Mysql 如何查询时间段交集

mysql 查询时间段交集

使用场景

数据库表有两个字段starttime,endtime。现在给出(a,b)的时间段,查出和(starttime,endtime)时间段有交集的数据。

sql

select * from tablename where  
    (starttime > a and starttime < b) or 
    (starttime < a and endtime > b) or
    (endtime > a and endtime < b) or
    (starttime = a and endtime = b);

mysql 查询两个时间段是否有交集的情况

数据库的字段 start_time, end_time

输入的字段 a,b

第一种

select * from test_table
where
    (start_time >= a and start_time <= b)
    or (start_time <= a and end_time >= b)
    or (end_time >= a and end_time <= b)

第二种

select * from test_table
where
    not (
        (end_time < a
        or (start_time > b)
    )

两种结果相同。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持www.887551.com。

(0)
上一篇 2022年3月21日
下一篇 2022年3月21日

相关推荐