mysql选择两个日期之间的数据,Mysql:选择两个日期之间的所有数据

I have a mysql table with data connected to dates. Each row has data and a date, like this:

2009-06-25 75

2009-07-01 100

2009-07-02 120

I have a mysql query that select all data between two dates. This is the query:

SELECT data FROM tbl WHERE date BETWEEN date1 AND date2

My problem is that I also need to get the rows between date1 and date2 even if there is no data for a day.

So my query would miss the dates that are empty between 2009-06-25 and 2009-07-01.

Can I in some way add these dates with just 0 as data?

解决方案

You can use a concept that is frequently referred to as 'calendar tables'. Here is a good guide on how to create calendar tables in MySql:

-- create some infrastructure

CREATE TABLE ints (i INTEGER);

INSERT INTO ints VALUES (0), (1), (2), (3), (4), (5), (6), (7), (8), (9);

-- only works for 100 days, add more ints joins for more

SELECT cal.date, tbl.data

FROM (

SELECT '2009-06-25' + INTERVAL a.i * 10 + b.i DAY as date

FROM ints a JOIN ints b

ORDER BY a.i * 10 + b.i

) cal LEFT JOIN tbl ON cal.date = tbl.date

WHERE cal.date BETWEEN '2009-06-25' AND '2009-07-01';

You might want to create table cal instead of the subselect.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值