Mysql介于两者之间

时间:2014-03-26 11:02:32

标签: mysql sql between

如何在2个日期之间的2个日期之间选择数据?例如:

start_date - end_date -- title

2014-01-28 2014-02-03 test

2014-02-01 2014-02-15 ests

2014-02-28 2014-03-03 sets

2014-03-01 2014-03-10 sste

问题是,我想在2014-02-02和之间选择数据 2014-02-28与前三名选中因为前三名 数据包含在第二个月。

我尝试了这个,但没有效果

SELECT title FROM my_tables WHERE start_date BETWEEN 2014-02-02 AND 2014-02-28

它是如何工作的?

3 个答案:

答案 0 :(得分:2)

当一个在另一个结束之前开始,而另一个在第一个开始之后结束时,两个周期重叠。这是正确的逻辑:

SELECT title
FROM my_tables
WHERE start_date <= '2014-02-28' and
      end_date >= '2014-02-02';

请注意,日期常量必须使用单引号。

Here是一个SQL小提琴,显示它正常工作。

答案 1 :(得分:0)

将单引号添加到日期常量

SELECT title FROM my_tables WHERE start_date BETWEEN '2014-02-02' AND '2014-02-28'

答案 2 :(得分:0)

当开头或结尾在另一个范围内时,日期范围与另一个重叠:

given range:    |----|
range 1     |----|           overlaps with given range, because end_date is in that range
range 2            |----|    overlaps with given range, because start_date is in that range
range 3  |----|              does not overlap with given range, because both start and end date are not in that range
SELECT title FROM my_tables 
WHERE (start_date BETWEEN '2014-02-02' AND '2014-02-28')
OR (end_date BETWEEN '2014-02-02' AND '2014-02-28');