我需要在2015-1-1和2015-12-12之间生成日期 我最近的代码在这里
set @startdate = '2015-1-10';
set @enddate = '2015-12-12';
select a.Date
from (
select curdate() - INTERVAL (a.a + (10 * b.a) - (100 * c.a)) DAY as Date
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) as a
cross join (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) as b
cross join (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) as c
) a where a.Date between @startdate and @enddate
从这段代码我有结果截断日期从2015年7月29日开始, 但如果代码设置日期在2016-01-01和2016-12-31之间,则结果将生成完整日期(完美)
感谢您的帮助
答案 0 :(得分:1)
我怀疑问题在于将值转换为字符串以进行比较。
我只想将格式更改为真正的YYYY-MM-DD:
set @startdate = '2015-01-10';
-----------------------^
set @enddate = '2015-12-12';
但是,date
功能也可能有效:
where a.Date between date(@startdate) and date(@enddate)
编辑:
我认为你有两个问题。首先,您的算术已关闭,您正在混合+
和-
。其次,你正在做与当前日期相关的所有事情。您应该使用开始日期。所以:
select a.Date
from (select date_add(date(startdate), INTERVAL (a.a + (10 * b.a) + (100 * c.a)) DAY) as Date
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) as a
cross join (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) as b
cross join (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) as c
) a
where a.Date between @startdate and @enddate;