MySQL 查询 INTERVAL 问题,如果没有提供数据则需要 0
我有以下声明:
SELECT
count(rs.rsc_id) as counter
FROM shots as rs
where rsc_rs_id = 345354
AND YEAR(rs.timestamp) = YEAR(DATE_SUB(CURDATE(), INTERVAL 6 MONTH))
GROUP BY DATE_FORMAT(rs.timestamp,'%Y%m')
rs.timestamp 是一个 unix 时间戳
输出就像每行/月的数字,如“28”
它工作正常,但如果我的数据不一致,例如仅过去三个月的数据(不适用于所有数据)六个月),我没有从数据库中得到任何回报。我想每次没有这个月的数据时,都会返回 0...
有什么建议吗? 我考虑了一些案例陈述,但这似乎不太好......
谢谢!
i have the following statement:
SELECT
count(rs.rsc_id) as counter
FROM shots as rs
where rsc_rs_id = 345354
AND YEAR(rs.timestamp) = YEAR(DATE_SUB(CURDATE(), INTERVAL 6 MONTH))
GROUP BY DATE_FORMAT(rs.timestamp,'%Y%m')
rs.timestamp is a unix timestamp
Output would be like for each row / month a numeric like '28'
It Works fine, but if i have inconsistent data, like only for the past three month (not for all six month), i get no return from my Database. I would like to have every time there is not data for this month, 0 returned...
any suggestion?
i thought about some case statements, but this seems not so good...
thanks!!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
仅 6 个月,日期表似乎没有必要,尽管这看起来很复杂(实际上并非如此!)
For only 6 months, a date table seems unnecessary, although this looks complicated (it really isn't!)
在这种情况下,通常使用包含所有日期(例如从 1970 年 1 月 1 日到 2999 年 12 月 31 日)的
日期
表,并将您的数据LEFT JOIN
添加到该表中。桌子。请参阅此处答案中的示例: mysql 连接创建缺失日期的表
如果您创建一个您可以使用的日期表:
In such cases it's common to use a table of
dates
with all dates (e.g. from 1/1/1970 to 31/12/2999) andLEFT JOIN
your data to that table.See an example in the answer here: mysql joins tables creating missing dates
If you create a dates table you can use: