2013-07-21 21 views
1

我的MySQL表有一个包含开始和结束日期作为时间戳的记录。在一段时间范围内查找月份

id(int)| dtBeg(时间戳)| dtEnd(时间戳)

我尝试选择在时间范围内具有给定月份的记录。

例如:

ID(INT)| dtBeg(时间戳)| dtEnd(timestamp)

1 | '2013-06-20'| '2013-08-20'

2 | '2013-07-20'| '2013-09-20'

2 | '2013-07-25'| '2013年7月28日'

记录发生在六月:1个

记录在七月发生的事情:1,2,3

记录在八月发生的事情:1,2

记录发生在九月:2

目前我不知道什么可能是一个很好的方法来处理日期范围,所以我可以提取几个月。我想到的唯一解决方案是复杂的方式,我相信有一个简单而明智的方法来做到这一点。

回答

2

对于这样的比较,我想将日期时间转换为“零时以来的月份”。你,你可以用算术进行计算。

您的查询,这看起来像:

select t.*, year(compdate), month(compdate) 
from t cross join 
    (select date('2013-07-01') as compdate) const 
where year(compdate)*12+month(compdate) between year(dtBeg)*12 + month(dtBeg) and 
               year(dtEnd)*12 + month(dtEnd); 

在这里,我已经把compdate在子查询。这样,如果您想检查多个月,则可以将表添加到表中:

select t.*, year(compdate), month(compdate) 
from t cross join 
    (select date('2013-07-01') as compdate union all 
     select date('2013-08-01') 
    ) const 
where year(compdate)*12+month(compdate) between year(dtBeg)*12 + month(dtBeg) and 
               year(dtEnd)*12 + month(dtEnd); 

此表单可以在许多SQL方言中使用。你可以使用date_format()做类似于MySQL特定功能的操作。

select t.*, year(compdate), month(compdate) 
from t cross join 
    (select '2013-07' as compdate union all 
     select '2013-08' 
    ) const 
where compdate between date_format(dtBeg, '%Y-%m') and date_format(dtEnd, '%Y-%m) 
+0

谢谢你,你的解决方案完美。现在我必须明白为什么:)。 – SirKometa