如何在mysql选择查询中获取两个日期之间的日期列表

时间:2012-02-15 14:55:44

标签: mysql sql

我希望日期列表位于选择查询的两个日期之间。例如:

如果我给'2012-02-10'和'2012-02-15'我需要结果。

date      
----------
2012-02-10
2012-02-11
2012-02-12
2012-02-13
2012-02-14
2012-02-15 

我怎么能得到?

6 个答案:

答案 0 :(得分:95)

尝试:

select * from 
(select adddate('1970-01-01',t4.i*10000 + t3.i*1000 + t2.i*100 + t1.i*10 + t0.i) selected_date from
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t0,
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t1,
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t2,
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t3,
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t4) v
where selected_date between '2012-02-10' and '2012-02-15'

- 未来的日期范围可达近300年。

[根据UrvishAtSynapse的建议编辑进行了更正。]

答案 1 :(得分:21)

set @i = -1;
SELECT DATE(ADDDATE('2012-02-10', INTERVAL @i:=@i+1 DAY)) AS date FROM `table`
HAVING 
@i < DATEDIFF('2012-02-15', '2012-02-10') 

这将完全按照规定返回结果集。此查询仅要求您更改datediff和adddate中的两个不同日期。

答案 2 :(得分:10)

在MySQL 5.5中,接受的答案对我不起作用。 我更新了查询以便为我工作:

select * from 
(select adddate('1970-01-01',t4*10000 + t3*1000 + t2*100 + t1*10 + t0) selected_date from
 (select 0 t0 union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t0,
 (select 0 t1 union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t1,
 (select 0 t2 union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t2,
 (select 0 t3 union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t3,
 (select 0 t4 union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t4) v
where selected_date between '2012-02-10' and '2012-02-15'

答案 3 :(得分:2)

您可以创建一个包含您可能需要使用的所有日期的表格:

date
2000-01-01
2000-01-02
2000-01-03
...etc..
2100-12-30
2100-12-31

然后按如下方式查询该表:

SELECT date
FROM dates
WHERE date BETWEEN '2012-02-10' AND '2012-02-15'

答案 4 :(得分:1)

看一下这篇文章:Get a list of dates between two dates

检查Ron Savage所做的存储过程,这似乎符合您的需求!

答案 5 :(得分:-5)

SELECT * FROM tablexxx WHERE datecol BETWEEN '2012-02-10' AND '2012-02-15';