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

Mysql: Select all data between two dates(Mysql:选择两个日期之间的所有数据)
本文介绍了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

我有一个 mysql 查询,用于选择两个日期之间的所有数据.这是查询:

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

我的问题是,即使一天没有数据,我也需要获取 date1 和 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.

所以我的查询会错过 2009-06-25 和 2009-07-01 之间的空日期.

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

我可以以某种方式添加这些只有 0 作为数据的日期吗?

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

推荐答案

您可以使用一个经常被称为日历表"的概念.这里是关于如何创建日历表的很好的指南在 MySql 中:

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';

您可能想要创建表 cal 而不是子选择.

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

这篇关于Mysql:选择两个日期之间的所有数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

ibtmp1是非压缩的innodb临时表的独立表空间,通过innodb_temp_data_file_path参数指定文件的路径,文件名和大小,默认配置为ibtmp1:12M:autoextend,也就是说在文件系统磁盘足够的情况下,这个文件大小是可以无限增长的。 为了避免ibtmp1文件无止境的暴涨导致
What does SQL clause quot;GROUP BY 1quot; mean?(SQL 子句“GROUP BY 1是什么意思?意思是?)
MySQL groupwise MAX() returns unexpected results(MySQL groupwise MAX() 返回意外结果)
MySQL SELECT most frequent by group(MySQL SELECT 按组最频繁)
Include missing months in Group By query(在 Group By 查询中包含缺失的月份)
Why Mysql#39;s Group By and Oracle#39;s Group by behaviours are different(为什么 Mysql 的 Group By 和 Oracle 的 Group by 行为不同)