Mysql 查询 - Return 两个日期范围相交的日期

Mysql query - Return dates where two date ranges intersect

我正在尝试编写一个 MySql 查询,其中两个日期范围相交。

例如,我想 return 从存在给定日期的 table 开始的一行。

所以我的用户可以 select 两个日期 'startdate'、'enddate'

我查了一下table

id, fromdate, tildate

在这个table中我有2行

id:1, fromdate:'2021-01-03', tildate:'2021-01-05'
id:2, fromdate:'2021-01-05', tildate:'2021-01-08'

现在如果用户使用以下值查询数据库:

startdate: '2021-01-01',  enddate '2021-01-02' - Should return nothing
startdate: '2021-01-03',  enddate '2021-01-04' - Should return 1, since there is an intersection
startdate: '2021-01-02',  enddate '2021-01-06' - Should return id 1 and 2, since there is an intersection in both
startdate: '2021-01-05',  enddate '2021-01-05' - Should return id 1 and 2, since there is an intersection in both
startdate: '2021-01-07',  enddate '2021-01-08' - Should return 2, since there is an intersection

我试过这个查询

SELECT 
   id, fromdate, todate FROM table_name 
WHERE 
    ('2021-01-02' >= fromDate
     AND '2021-01-02' <= toDate)
OR
    ('2021-01-06' >= fromDate
    AND '2021-01-06' <= toDate)

这行不通。

希望这是有道理的

试试这个:

SELECT *
FROM table_name 
WHERE 
    ('2021-01-02' >= fromDate
     AND '2021-01-02' <= toDate)
OR
    ('2021-01-06' >= fromDate
    AND '2021-01-06' <= toDate)

您在查询中到处都使用了 fromDate,这可能是问题所在