我如何填补 MySQL 中的日期空白?这是我的查询:
SELECT DATE(posted_at) AS date, COUNT(*) AS total, SUM(attitude = 'positive') AS positive, SUM(attitude = 'neutral') AS neutral, SUM(attitude = 'negative') AS negative FROM `messages` WHERE (`messages`.brand_id = 1) AND (`messages`.`spam` = 0 AND `messages`.`duplicate` = 0 AND `messages`.`ignore` = 0) GROUP BY date ORDER BY date
它返回正确的结果集 - 但我想用零填充开始日期和结束日期之间的空白。我该怎么做?
最佳答案
您需要创建一个辅助表并用从start
到end
的所有日期填充它,然后用它LEFT JOIN
表:
SELECT d.dt AS date,
COUNT(*) AS total,
SUM(attitude = 'positive') AS positive,
SUM(attitude = 'neutral') AS neutral,
SUM(attitude = 'negative') AS negative
FROM dates d
LEFT JOIN
messages m
ON m.posted_at >= d.dt
AND m.posted_at < d.dt + INTERVAL 1 DAYS
AND spam = 0
AND duplicate = 0
AND ignore = 0
GROUP BY
d.dt
ORDER BY
d.dt
基本上,您在这里需要的是一个虚拟行源。
MySQL
是唯一缺少生成它的方法的主要系统。
PostgreSQL
实现了一个特殊的函数 generate_series
来做到这一点,而 Oracle
和 SQL Server
可以使用递归( CONNECT BY
和相应的递归 CTE
。
关于sql - 如何填补 MySQL 中的日期空白?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1877874/