I have two db tables:
tasks:
task_id (unique id, autoincrement)
group_id (from the next table: groups, where task belongs to)
task_name
status (if task has been completed or not)
groups:
group_id (unique id, autoincrement)
group_name
My goal is to list all groups along with number of uncompleted tasks in them (task status 0).
I achieve that by this query:
$sql_query = "SELECT g.id, g.name, count(g.id) as count
FROM task_groups g, tasks t
WHERE g.status = 0 AND t.group = g.id AND t.status = 0
GROUP BY g.id
ORDER BY g.id ASC";
And I get results like this:
Group1 3 uncompleted Group2 13 uncompleted Group3 30 uncompleted
But empty task groups (there are no any tasks that belong to a specific group) are not being listed.
Result should be like this:
Group1 3 uncompleted Group2 13 uncompleted Group3 30 uncompleted Group4 0 uncompleted Group5 0 uncompleted
How can I achieve that?
You’re on the right track.
GROUP BYthe group, but instead of counting the group id, try instead doing aSUMon tasks that are incomplete, like this:Omit the
HAVINGclause if you want to list all task groups.Note: I didn’t see the purpose of
g.statusin your query, andstatuswasn’t listed as a column in thegroupstable so I’ve left it out of my example.