我有一个数据库表如下:
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 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
关于MySQL 从数据库表中不存在记录的范围中获取日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58935957/