【问题标题】:mysql group by date(day) not showing if no result in specific day [duplicate]如果在特定日期没有结果,mysql按日期(天)分组不显示[重复]
【发布时间】:2014-03-23 20:41:21
【问题描述】:

这是我的查询

select sender, count(*) as Total, date_format(senttime, '%m - %Y - %d') as Sent_Date 
from sendmail sm 
left join subuser su 
   on (sm.sender = su.sub_user) 
where senttime <= NOW() 
  AND senttime >= DATE_SUB(senttime, INTERVAL 7 DAY) 
group by date_format(senttime, '%d'), sender

这是实际输出

它只显示两个日期 2122 但我需要 7 个日期,总计数为 0。

我该怎么做。

【问题讨论】:

  • 虽然您的输出截图很有帮助,但可能更有帮助的是示例数据和所需输出,最好只是列出有问题或放入 sqlfiddle.com

标签: php mysql sql


【解决方案1】:

好吧,如果没有发送时间,则不满足您的where条件。

where senttime <= NOW() 
AND senttime >= DATE_SUB(senttime, INTERVAL 7 DAY) 

你需要给它添加一个or

where senttime IS NULL OR (senttime <= NOW() 
AND senttime >= DATE_SUB(senttime, INTERVAL 7 DAY))

你可能需要切换这个

from sendmail sm 
left join subuser su 

from subuser su 
left join sendmail sm

假设 sendmail 仅在发送某些内容时才具有值 - 您需要从您知道会出现的那个中进行选择,然后离开加入您不确定的那个(或进行不同类型的加入)

【讨论】:

  • 使用RIGHT JOIN 的绝佳机会刚刚路过您。
  • 因此是“或做不同类型的加入”评论 - 但我认为就左连接而言,所以永远不要真正做右连接。
  • 我不怪你,大多数人都忽略了穷人RIGHT JOIN
猜你喜欢
  • 2012-11-06
  • 2011-10-07
  • 2010-11-06
  • 2021-08-10
  • 2012-10-22
  • 1970-01-01
  • 1970-01-01
  • 2019-06-30
  • 2015-11-20
相关资源
最近更新 更多