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:选择两个日期之间的所有数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

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

相关文档推荐

Can#39;t Create Entity Data Model - using MySql and EF6(无法创建实体数据模型 - 使用 MySql 和 EF6)
MySQL select with CONCAT condition(MySQL选择与CONCAT条件)
Capitalize first letter of each word, in existing table(将现有表格中每个单词的首字母大写)
How to retrieve SQL result column value using column name in Python?(如何在 Python 中使用列名检索 SQL 结果列值?)
Update row with data from another row in the same table(使用同一表中另一行的数据更新行)
Exporting results of a Mysql query to excel?(将 Mysql 查询的结果导出到 excel?)