在 MySQL 中的 generate_series() 等效

generate_series() equivalent in MySQL(在 MySQL 中的 generate_series() 等效)
本文介绍了在 MySQL 中的 generate_series() 等效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我需要进行查询并加入一年中的所有日子,但在我的数据库中没有日历表.
在 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-012011-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() 等效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

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

相关文档推荐

ibtmp1是非压缩的innodb临时表的独立表空间,通过innodb_temp_data_file_path参数指定文件的路径,文件名和大小,默认配置为ibtmp1:12M:autoextend,也就是说在文件系统磁盘足够的情况下,这个文件大小是可以无限增长的。 为了避免ibtmp1文件无止境的暴涨导致
SQL query to group by day(按天分组的 SQL 查询)
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 查询中包含缺失的月份)