MySQL JOIN with where子句和group by count

时间:2015-12-26 04:46:09

标签: php mysql join group-by

我运行以下查询,

SELECT status.status_id, status.status_name, COUNT(workbin.status_id)
FROM `status`
LEFT JOIN `workbin` ON workbin.status_id = status.status_id
GROUP BY status.status_id

并获得输出

status_id status_name count
1   New              44
2   On Hold          1
3   In Analysis      2
4   In Development   12
5   In Testing       17
6   In Release       2
7   Completed        151
8   In Review        0
9   Unit Testing     0
11  Rework           0
12  Reopen           0

现在我需要在此查询中添加一个where子句,以根据workbin表中的用户ID来检索数据。因此结果将仅显示用户的计数。用户标识也存储在workbin表中。

如果我添加where子句WHERE workbin . task_assigned_id = 37 并且发现缺少一些status_id和status_name(其值为0)。 但我需要分配给用户的任务的所有状态计数(workbin.task_assigned_id)。

1 个答案:

答案 0 :(得分:0)

这是因为通过WHERE子句,您指定仅显示task_assigned_id = 37表中具有值workbin的记录。所以,你不能得到你在workbin表中没有行的行(即使它在status表中。)解决方案可以是这样的,以保持条件WHERE部分中的LEFT JOIN条款:

SELECT status.status_id, status.status_name, COUNT(workbin.status_id)
FROM `status`
LEFT JOIN `workbin` ON workbin.status_id = status.status_id AND workbin.task_assigned_id= 37
GROUP BY status.status_id