Mysql 在时间范围内查找月份

Mysql 在时间范围内查找月份,mysql,sql,datetime,select,Mysql,Sql,Datetime,Select,我有一个MySQL表,其中的记录包含开始日期和结束日期作为时间戳 id(int)| dtBeg(时间戳)| dtEnd(时间戳) 我尝试选择在时间范围内具有给定月份的记录 例如: id(int)| dtBeg(时间戳)| dtEnd(时间戳) 1 |“2013-06-20”|“2013-08-20” 2 |“2013-07-20”|“2013-09-20” 2 |“2013-07-25”|“2013-07-28” 六月份的纪录:1 7月份发生的记录:1、2、3 8月份发生的记录:1,2 九月份的

我有一个MySQL表,其中的记录包含开始日期和结束日期作为时间戳

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

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

例如:

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

1 |“2013-06-20”|“2013-08-20”

2 |“2013-07-20”|“2013-09-20”

2 |“2013-07-25”|“2013-07-28”

六月份的纪录:1

7月份发生的记录:1、2、3

8月份发生的记录:1,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\u 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)