我需要在sql中生成两个日期之间的天数,如下所示:
我正在使用此查询:
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
效果很好,但总会产生1000天。我怎样才能生成像365这样的其他天数?
答案 0 :(得分:0)
您可以添加限制条款(和订单)
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
order by 1 desc
limit 365
答案 1 :(得分:0)
或者,如果允许以更易读的方式创建临时表 - 并且可以非常容易地扩展到10,000个整数或更多:
CREATE TEMPORARY TABLE units(idx)
ENGINE=MEMORY
AS (
SELECT 0
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
);
SELECT a.the_date
FROM (
SELECT curdate() - INTERVAL (hundreds + tens + units) DAY AS the_date
FROM (SELECT idx AS units FROM units) units
CROSS JOIN (SELECT idx* 10 AS tens FROM units) tens
CROSS JOIN (SELECT idx* 100 AS hundreds FROM units) hundreds
WHERE hundreds + tens + units < 365
) AS a
ORDER BY 1
;