问题描述
我需要进行查询并加入一年中的所有日子,但在我的数据库中没有日历表.
在 google-ing 之后,我在 PostgreSQL 中找到了 generate_series()
.MySQL有没有类似的东西?
I need to do a query and join with all days of the year but in my db there isn't a calendar table.
After google-ing I found generate_series()
in PostgreSQL. Does MySQL have anything similar?
我的实际表类似于:
date qty
1-1-11 3
1-1-11 4
4-1-11 2
6-1-11 5
但我的查询必须返回:
1-1-11 7
2-1-11 0
3-1-11 0
4-1-11 2
and so on ..
推荐答案
我就是这样做的.它创建了从 2011-01-01 到 2011-12-31 的日期范围:
This is how I do it. It creates a range of dates from 2011-01-01 to 2011-12-31:
select
date_format(
adddate('2011-1-1', @num:=@num+1),
'%Y-%m-%d'
) date
from
any_table,
(select @num:=-1) num
limit
365
-- use limit 366 for leap years if you're putting this in production
唯一的要求是 any_table 中的行数应大于或等于所需范围的大小(在本例中为 >= 365 行).您很可能会将其用作整个查询的子查询,因此在您的情况下,any_table 可以是您在该查询中使用的表之一.
The only requirement is that the number of rows in any_table should be greater or equal to the size of the needed range (>= 365 rows in this example). You will most likely use this as a subquery of your whole query, so in your case any_table can be one of the tables you use in that query.
这篇关于在 MySQL 中的 generate_series() 等效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!