如何在两个日期之间创建所有月份名称的列表,例如1月,2月等。例如2012-02-01至2013-03-29与MySQL ..而2月将生成两次,一次为2012年,另一次为2013
答案 0 :(得分:9)
我想这就是你要找的东西:
select MonthName(aDate) from (
select @maxDate - interval (a.a + (10 * b.a) + (100 * c.a)) month as aDate from
(select 0 as a union all select 1 union all select 2 union all select 3
union all select 4 union all select 5 union all select 6 union all
select 7 union all select 8 union all select 9) a,
(select 0 as a union all select 1 union all select 2 union all select 3
union all select 4 union all select 5 union all select 6 union all
select 7 union all select 8 union all select 9) b,
(select 0 as a union all select 1 union all select 2 union all select 3
union all select 4 union all select 5 union all select 6 union all
select 7 union all select 8 union all select 9) c,
(select @minDate := '2012-02-01', @maxDate := '2013-03-29') d
) e
where aDate between @minDate and @maxDate
万一有人发现这篇文章并发现它有点难以理解,我只是添加一个简短的解释:
这是一个动态(并且有点难看)的解决方案,用于创建不需要创建表的日期范围,并且基于以下查询为大多数应用程序生成足够的记录(10000条记录):
select aDate from (
select @maxDate - interval (a.a+(10*b.a)+(100*c.a)+(1000*d.a)) day aDate from
(select 0 as a union all select 1 union all select 2 union all select 3
union all select 4 union all select 5 union all select 6 union all
select 7 union all select 8 union all select 9) a, /*10 day range*/
(select 0 as a union all select 1 union all select 2 union all select 3
union all select 4 union all select 5 union all select 6 union all
select 7 union all select 8 union all select 9) b, /*100 day range*/
(select 0 as a union all select 1 union all select 2 union all select 3
union all select 4 union all select 5 union all select 6 union all
select 7 union all select 8 union all select 9) c, /*1000 day range*/
(select 0 as a union all select 1 union all select 2 union all select 3
union all select 4 union all select 5 union all select 6 union all
select 7 union all select 8 union all select 9) d, /*10000 day range*/
(select @minDate := '2001-01-01', @maxDate := '2002-02-02') e
) f
where aDate between @minDate and @maxDate
根据日期范围的长度,您可以通过删除表格(d,c,b和a依次)来减少动态生成结果的数量(10000天意味着超过27年的记录,每个代表一天)也从上面的公式中删除它们。通过设置@minDate
和@maxDate
变量,您可以指定要过滤结果的日期。