MySQL从数据库表中不存在记录的范围中获取日期

问题描述 投票:1回答:1

我具有如下数据库表:

 Sales Table 
id  product_id  for_date
 1          10  2019-01-03
 2          12  2019-01-05
 3          16  2019-01-10

我想从表中没有记录的自定义日期范围之间获取日期。例如。我想获取没有销售的日期为2019-01-01至2019-01-31,即所有日期为2019-01-01至2019-01-31,但不包括2019-01-03、2019-01- 2019年5月5日。谁能帮我这个忙。预先感谢。

mysql sqldatetime
1个回答
2
投票

典型的解决方案将包括日历表,该表存储您要检查订单是否存在的所有日期。

如果您运行的是MySQL 8.0,则可以使用递归查询轻松地生成日历表。

考虑:

with recursive cte as (
    select '2019-01-01' dt
    union all
    select dt + interval 1 day from cte where dt < '2019-01-31'
)
select c.dt 
from cte c
left join sales s on s.for_date = c.dt
where s.for_date is null

注意:如果性能很重要,则最好实现日历表(即将其存储为表),而不是即时生成日历表。相同的递归查询可用于此:

create table mycalendar as 
with recursive cte as (
    select '2019-01-01' dt
    union all
    select dt + interval 1 day from cte where dt < '2019-01-31'
)
select * from cte;

然后:

select c.dt 
from mycalendar c
left join sales s on s.for_date = c.dt
where s.for_date is null
© www.soinside.com 2019 - 2024. All rights reserved.