簡體   English   中英

在 MySQL 中的 generate_series() 等效

[英]generate_series() equivalent in MySQL

我需要進行查詢並加入一年中的所有日子,但在我的數據庫中沒有日歷表。
在 google-ing 之后,我在 PostgreSQL 中找到了generate_series() MySQL有沒有類似的東西?

我的實際表有類似的東西:

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的日期范圍:

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可以是您在該查詢中使用的表之一。

來自@Karolis 的增強版解決方案,確保它適用於任何年份(包括閏年):

select date from (
    select
        date_format(
        adddate('2011-1-1', @num:=@num+1),
        '%Y-%m-%d'
    ) date
    from
        any_table,
    (select @num:=-1) num
    limit
        366
) as dt
where year(date)=2011

我正在尋找這個解決方案,但沒有“硬編碼”日期,我想出了這個對當年有效的解決方案(從這個答案中得到幫助)。 請注意

where year(date)=2011

不需要,因為選擇已經過濾了日期。 同樣這樣,使用哪個表(至少如表至少有 366 行之前所述)並不重要,因為日期是在運行時“計算”的。

 select date from (
    select
        date_format(
        adddate(MAKEDATE(year(now()),1), @num:=@num+1),
        '%Y-%m-%d'
    ) date
    from
        your_table,
    (select @num:=-1) num
    limit
        366 ) as dt

以防萬一有人正在尋找 generate_series() 來生成一系列日期或整數作為 MySQL 中的臨時表。

使用 MySQL8(MySQL 版本 8.0.27)你可以做這樣的事情來模擬:

WITH RECURSIVE nrows(date) AS (
SELECT MAKEDATE(2021,333) UNION ALL 
SELECT DATE_ADD(date,INTERVAL 1 day) FROM nrows WHERE  date<=CURRENT_DATE
)
SELECT date FROM nrows;

結果:

2021-11-29
2021-11-30
2021-12-01
2021-12-02
2021-12-03
2021-12-04
2021-12-05
2021-12-06

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM