从两个日期检查两个日期列之间的日期mySQL

时间:2019-03-14 07:09:53

标签: mysql sql

我要检查记录是否存在。

表1:

  S.No    StartDate         EndDate
 -------------------------------------
  1.      2019-10-15        2019-10-20
  2.      2019-10-10        2019-10-13
  3.      2019-10-21        2019-10-25

如果根据以下任何一种情况满足任何条件,我需要获取数据。

情况1: 如果date_from: 2019-10-17 和date_to: 2019-10-19

输出:

  S.No    StartDate         EndDate
 -------------------------------------
  1.      2019-10-15        2019-10-20

案例2: 如果date_from: 2019-10-14 和date_to: 2019-10-21

输出:

  S.No    StartDate         EndDate
 -------------------------------------
  1.      2019-10-15        2019-10-20
  3.      2019-10-21        2019-10-25

情况3: 如果date_from: 2019-10-13 和date_to: 2019-10-16

输出:

  S.No    StartDate         EndDate
 -------------------------------------
  1.      2019-10-15        2019-10-20
  2.      2019-10-10        2019-10-13

案例4: 如果date_from: 2019-10-17 和date_to: 2019-10-20

输出:

  S.No    StartDate         EndDate
 -------------------------------------
  1.      2019-10-15        2019-10-20

案例5: 如果date_from: 2019-11-17 和date_to: 2019-11-20

输出:

  *No records

这是我尝试过的:

查询1:

SELECT * FROM Table1
WHERE StartDate BETWEEN **date_from** AND **date_to**
OR EndDate BETWEEN **date_from** AND **date_to**

Query2:

SELECT * FROM Table1
WHERE **date_from** BETWEEN StartDate AND EndDate 
OR **date_to** BETWEEN StartDate AND EndDate

我已经尝试过以下解决方案:

Check two date was not between two another date + MYSQl

check given date exists between two date column in mysql

2 个答案:

答案 0 :(得分:2)

这是重叠的日期范围问题。这是您第一种情况的查询,您想在2019-10-172019-10-19之间找到匹配的记录:

SELECT *
FROM yourTable
WHERE EndDate >= '2019-10-17' AND StartDate <= '2019-10-19';

更一般地:

SELECT *
FROM yourTable
WHERE EndDate >= <date_from> AND StartDate <= <date_to>;

如果您想在一个查询中包含两个日期范围,则可以简单地展开WHERE子句:

SELECT *
FROM yourTable
WHERE
    (EndDate >= '2019-10-13' AND StartDate <= '2019-10-16') OR
    (EndDate >= '2019-10-17' AND StartDate <= '2019-10-19');

答案 1 :(得分:-1)

对于以上所有情况,此解决方案都对我有效

SELECT * FROM Table1
WHERE ( StartDate <= 'date_from' and EndDate >= 'date_from' )
OR ( 'date_from' <= StartDate and 'date_to' >= StartDate )
OR ( StartDate < 'date_to' and EndDate >= 'date_to' )

参考:

SQL query to search for room availability