【问题标题】:MySQL get dates from a range for which the records does not exist in the database tableMySQL 从数据库表中不存在记录的范围中获取日期
【发布时间】:2019-11-19 14:08:24
【问题描述】:

我有一个如下的数据库表:

 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- 05,2019-01-10。 任何人都可以帮助我解决这个问题。提前致谢。

【问题讨论】:

  • 考虑处理应用代码中数据显示的问题。

标签: mysql sqldatetime


【解决方案1】:

对此的典型解决方案包括一个日历表,其中存储了您要检查订单是否存在的所有日期。

如果您运行的是 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-21
    • 1970-01-01
    • 2015-09-30
    • 1970-01-01
    • 2021-11-22
    相关资源
    最近更新 更多