简体   繁体   English

获取 MySQL 中 2 个日期之间的日期?

[英]Get dates between 2 dates in MySQL?

How do you get list of dates inside of 2 dates?你如何获得2个日期内的日期列表?

Currently in my booking table I have 2 fields like starts_at and ends_at目前在我的booking表中有 2 个字段,例如starts_atends_at

If I use a query something like this如果我使用这样的查询

SELECT starts_at, ends_at FROM booking

This will give me all of records exists这将给我所有存在的记录

在此处输入图像描述

But what I want is to list all of dates records uniquely但我想要的是唯一列出所有日期记录

Let say in the first row of record 2020-08-19 to 2020-09-16让我们在记录的第一行说2020-08-192020-09-16

This will be the output这将是 output

    2020-08-19
    2020-08-20
    2020-08-21
    ......continuation
    2020-09-15
    2020-09-16

and on the second row there is 2020-06-04 to 2020-06-09第二行是2020-06-042020-06-09

This will be这将成为;这将是

 2020-06-04
 2020-06-05
 2020-06-06
 2020-06-07
 2020-06-08
 2020-06-09

as you can see all between dates are being dropdown.如您所见,所有日期之间的内容都在下拉列表中。

and the final output of that should be the collected dates will be arranged based on the recent like this而最后的output应该是采集日期会按照最近的这样排

 2020-06-04 (added dates from 2nd row)  
 2020-06-05
 2020-06-06
 2020-06-07
 2020-06-08
 2020-06-09

 2020-08-19 (added dates from 1st row)
 2020-08-20
 2020-08-21
 ......continuation
 2020-09-15
 2020-09-16

Just in case some dates are being duplicated it should be counted/read as one.以防万一某些日期被重复,它应该被计为/读取为一个。 since all days are being arranged.因为所有的日子都在安排中。

For MySQL 8+对于 MySQL 8+

WITH RECURSIVE
cte AS ( SELECT starts_at, ends_at, starts_at single_date 
         FROM booking
         UNION ALL
         SELECT starts_at, ends_at, single_date + INTERVAL 1 DAY
         FROM cte
         WHERE single_date < ends_at )
SELECT DISTINCT single_date
FROM cte
ORDER BY 1;

For MySQL 5+ you must use generated numbers table with the numbers from 0 to at least MAX(ends_at - starts_at) :对于 MySQL 5+,您必须使用生成的数字表,其中数字从0到至少MAX(ends_at - starts_at)

SELECT DISTINCT booking.starts_at + INTERVAL n.n DAY single_date
FROM booking
-- assuming 99 days is enough
JOIN ( SELECT n1.n*10+n2.n n
       FROM (SELECT 0 n UNION SELECT 1 UNION ... UNION SELECT 9) n1
       JOIN (SELECT 0 n UNION SELECT 1 UNION ... UNION SELECT 9) n2 ) n
WHERE booking.starts_at + INTERVAL n.n DAY <= booking.ends_at;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM