我正在使用MySQL,我有以下表结构
Id id2 classId sectionId validFrom validTill
------------------------------------------------------
1 1 5 13 2016-01-01 2016-03-30
2 1 5 22 2016-01-15 2016-03-30
3 1 5 23 2016-01-15 2016-04-29
4 1 5 13 2016-04-01 2016-04-30
9 10 6 24 2016-01-17 2016-02-05
10 10 6 25 2016-01-23 2016-02-05
11 10 6 24 2016-01-31 2016-02-05
我的SQL语句是
SELECT count(*) as timeCount FROM TimeTableClassSection a
WHERE classId=5 AND sectionId=13 AND ((a.ValidFrom BETWEEN '2016-01-18' AND '2016-01-24') OR (a.ValidTill BETWEEN '2016-01-18' AND '2016-01-24'))
它返回timeCount = 0
。但它应该返回1作为记录,Id = 1落在此日期范围('2016-01-18' AND '2016-01-24')
我正在尝试实现,找出特定classId&的任何重叠记录。 sectionId在提供的日期范围之间。
如果classId=5
和sectionId=13
存在validFrom=2016-01-01
validTill=2016-03-30
,则此日期范围('2016-01-18' AND '2016-01-24')
之间的任何日期范围都应将此记录作为计数。
If I give date range 2015-12-25 to 2016-09-20 then record count should = 1
If I give date range 2016-2-1 to 2016-02-20 then record count should = 1
If I give date range 2016-2-1 to 2016-09-20 then record count should = 1
我在这里做错了...所有日期格式都在YYYY-MM-DD
答案 0 :(得分:0)
您只检查边界是否在日期范围内,但不检查数据范围是否在边界内。你应该扩展你的标准:
...AND ((a.ValidFrom BETWEEN '2016-01-18' AND '2016-01-24')
OR (a.ValidTill BETWEEN '2016-01-18' AND '2016-01-24')
OR (a.ValidFrom<'2016-01-18' AND a.ValidTill>'2016-01-24'))