MySQL JOIN with where clause and group by count

你。 提交于 2020-01-06 11:55:27

问题


I run a the following query,

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

and got the output

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

Now i need to add a where clause in this query, to retrive the data based on the user id in the workbin table. So the result will show only the count for the user. The user id is also stored in the workbin table.

If i add a where clause WHEREworkbin.task_assigned_id= 37 and found few status_id and status_name are missing(which have the 0 value). But i need all the status counts for the task assigned user(workbin.task_assigned_id).


回答1:


It's because by WHERE clause, you are specifying to show only the records which have a value task_assigned_id = 37 in workbin table. So, you cannot get the rows, for which you don't have a row in workbin table (even though it is in status table.) The solution can be something like this, to keep the conditions of your WHERE clause in LEFT JOIN part:

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


来源:https://stackoverflow.com/questions/34468566/mysql-join-with-where-clause-and-group-by-count

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!