I have two tables, tasks and status. Tasks table have columns task_id, project_id task_content and status_id. Status table have columns status_id and status_name. I want to get query which takes all status names and counts how much are there tasks with that status names. My query looks like this:
EDIT: i forgot to add project_id. Query needs to check only tasks within one project.
SELECT s.status_name, COUNT(t.status_id) AS tasks
FROM status s
LEFT JOIN tasks t
ON s.status_id = t.status_id
WHERE t.project_id = 1
GROUP BY s.status_name
My query is working good, but when there are no tasks with one of statuses this status is left out from query, i want it to show zero like:
status name | tasks
status 1 | 3
status 2 | 2
status 3 | 0
but my query looks like this:
status name | tasks
status 1 | 3
status 2 | 2
Thanks everyone for help, i found solution. I will post it for everyone who will have same or similar problem in future. Using 'WHERE' mess up my left join so there is workaround:
SELECT s.status_name, (IFNULL(COUNT(t.task_id), 0)) AS tasks
FROM status s
LEFT OUTER JOIN tasks t
ON s.status_id = t.status_id
AND t.project_id = 1
GROUP BY s.status_name
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With