MySQL:选择日期范围之间的所有日期,并获取匹配日期的表数据 [英] MySQL: Select all dates between date range and get table data matching dates
问题描述
有一个表,其中包含这样的数据:
There is a table which has data as such:
-----------------------
| id | date |
-----------------------
| 1 | 2016-07-11 |
| 2 | 2016-07-11 |
| 3 | 2016-07-15 |
| 4 | 2016-07-15 |
| 5 | 2016-07-15 |
| 6 | 2016-07-16 |
| 7 | 2016-07-19 |
| 8 | 2016-07-20 |
-----------------------
我想获取一个日期范围(所有日期)和每个日期的ID计数,如果不存在任何记录,则返回0.
I want to get a date range (all dates) and the count of IDs for each date, returning 0 when no records exist.
如果运行日期为2016年7月10日至2016年7月20日,则结果应如下所示:
If run for dates between 2016-07-10 to 2016-07-20, the result should look like this:
--------------------------
| date | count(id) |
--------------------------
| 2016-07-10 | 0 |
| 2016-07-11 | 2 |
| 2016-07-12 | 0 |
| 2016-07-13 | 0 |
| 2016-07-14 | 0 |
| 2016-07-15 | 3 |
| 2016-07-16 | 1 |
| 2016-07-17 | 0 |
| 2016-07-18 | 0 |
| 2016-07-19 | 1 |
| 2016-07-20 | 1 |
--------------------------
I've found solutions for getting a date range but couldn't figure out how to get it to count the IDs that exist for those dates within a table.
谢谢!
推荐答案
我通过修改解决方案中给出的查询以获取所有日期来解决这个问题.
I figured this out by modifying the query given in the solution for getting all dates.
以下查询返回所有日期,以及是否存在记录的ID计数:
The following query returns all dates, and counts of the IDs if any records exist:
select d.date, count(v.id) from
(select adddate('1970-01-01',t4.i*10000 + t3.i*1000 + t2.i*100 + t1.i*10 + t0.i) 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) d
left join visitors v on d.date = v.date
where d.date between '2016-06-01' and '2016-06-30'
group by d.date
order by d.date
要获取日期范围,请访问 @ mark-bannister ,并在查询上进行简单的联接以匹配结果,排序即可找到解决方案.
Courtesy for getting the dates range goes to @mark-bannister and a simple join on the query matching for results, and sorting gets the solution.
这篇关于MySQL:选择日期范围之间的所有日期,并获取匹配日期的表数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!