在日期之间检索记录

时间:2013-05-20 19:11:06

标签: mysql sql date datetime

我有以下查询,它将检索作为参数提供的开始日期和结束日期之间的事件:

SELECT * FROM events
WHERE (startDate BETWEEN CAST(@start AS DATETIME) AND CAST(@end AS DATETIME)
OR endDate BETWEEN CAST(@start AS DATETIME) AND CAST(@end AS DATETIME))

这适用于检索与开始和结束时间重叠的事件,但不会获取在这些时间之间完全封装的事件。一张图片可能会更清楚:

Event A |------------------------------------------------------------------| Event B ----------------------|------------|-------------------------------

Where | represents a start or end date

在我的图片中,使用我的查询以及事件B的开始和结束时间,它不会检索事件A.

如何更改查询以便显示所有重叠和封装的事件?

2 个答案:

答案 0 :(得分:2)

SELECT * FROM events
WHERE (startDate BETWEEN CAST(@start AS DATETIME) AND CAST(@end AS DATETIME)
OR endDate BETWEEN CAST(@start AS DATETIME) AND CAST(@end AS DATETIME))
OR (endDate >= CAST(@end AS DATETIME)) AND startDate <= CAST(@end AS DATETIME))

最后一行OR行将添加start小于end参数且end大于此值的所有行。这样,与@end重叠的所有行都将匹配。你也可以尝试:

SELECT * FROM events
WHERE 
 (startDate <= CAST(@start AS DATETIME)) AND endDate >= CAST(@start AS DATETIME))
OR (endDate >= CAST(@end AS DATETIME)) AND startDate <= CAST(@end AS DATETIME))

应该匹配你想要的一切。它匹配覆盖startend的每条记录。如果你想要匹配startend中包含的所有内容,但不要与它们中的任何内容重叠,也许你必须将它与它们结合起来。

答案 1 :(得分:1)

你必须做

SELECT * FROM events
WHERE (startDate <= CAST(@end AS DATETIME) AND endDate >= CAST(@start AS DATETIME)