【问题标题】:Count the number of exists and not exist using MySQL使用 MySQL 计算存在和不存在的数量
【发布时间】:2014-07-18 09:11:21
【问题描述】:

我正在尝试列出所有已完成/已完成任务计数的任务(提交中)。问题是我还想显示没有用户完成的所有任务。此查询未列出 count = 0 (Null)。有没有办法做到这一点?

想要的结果:

Date       | title   | completed
2014-05-20 | Case  1 | 45
2014-05-24 | Case 10 | 11
2014-05-20 | Case  2 |  0

到目前为止我已经尝试过:

Select date, title, count(*) as completed
from users u, submissions s, task t
where u.userPK = s.user
and s.task= t.taskPK
group by taskPK
order by completed desc; 

【问题讨论】:

  • datetitle 属于哪个表?
  • 日期和标题属于表格任务。
  • 你能举一个你想要的输出的例子吗,不太明白你的预期结果。
  • 我要列出已完成任务的数量,以及未完成的任务。由(0 或 null)表示。

标签: mysql count group-by


【解决方案1】:

您需要使用OUTER JOIN 来获得您想要的结果。但是,考虑到前面的答案还不够,我也猜你不想GROUP BYtaskPK 字段,而是datetitle 字段。

也许这就是你要找的东西:

SELECT t.date, t.title, count(*) cnt
FROM task t
    LEFT JOIN submissions s ON t.task = s.taskPK
GROUP BY t.date, t.title
ORDER BY cnt DESC

我还删除了user 表,因为我不确定它如何影响结果。如果您需要它,只需添加一个额外的连接。

【讨论】:

    【解决方案2】:

    我认为您应该能够使用LEFT JOIN

    SELECT date, title, COUNT(u.userPK) completed FROM task t 
    LEFT JOIN submissions s ON s.task = t.taskPK 
    LEFT JOIN users u ON s.user = u.userPK 
    GROUP BY t.taskPK 
    ORDER BY completed;
    

    【讨论】:

    猜你喜欢
    • 2012-04-04
    • 2013-11-29
    • 2013-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-10
    • 2013-03-31
    相关资源
    最近更新 更多