SQL查询以查找日期范围内的所有数据,该日期范围介于两个日期之间

时间:2016-05-24 05:27:06

标签: mysql sql hql hibernate-criteria

Task Table
id  name    start_date  expiry_date
1   Task 1  09-05-2016  11-05-2016
2   Task 2  10-05-2016  13-05-2016
3   Task 3  11-05-2016  12-05-2016 
4   Task 4  17-05-2016  20-05-2016
5   Task 5  18-05-2016  26-05-2016

我需要查找给定日期范围内的所有任务,其中范围内的每个日期都在start_date和expiry_date之间。假设输入为10-05-2016至12-05-2016。

id  name    start_date  expiry_date
1   Task 1  09-05-2016  11-05-2016
2   Task 2  10-05-2016  13-05-2016
3   Task 3  11-05-2016  12-05-2016 

2 个答案:

答案 0 :(得分:1)

您可以将此条件用于check if two date ranges overlap

WHERE 
    StartA <= EndB 
    AND EndA >= StartB

您的查询应该是:

SELECT *
FROM tbl
WHERE
    start_date <= '12-05-2016'
    AND expiry_date >= '10-05-2016'

答案 1 :(得分:0)

希望start_date始终小于expiry_date

SELECT * FROM Task WHERE start_date <= '12-05-2016' AND expiry_date >= '10-05-2016'