如何列出未完成任务的组和计数?

时间:2011-12-16 23:21:50

标签: mysql sql

我有两个数据库表:

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

我的目标是列出所有组以及其中未完成任务的数量(任务状态0)。 我通过这个查询实现了这个目标:

$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";

我得到的结果如下:

Group1  3 uncompleted
Group2 13 uncompleted
Group3 30 uncompleted

但是没有列出空任务组(没有任何属于特定组的任务)。

结果应该是这样的:

Group1  3 uncompleted
Group2 13 uncompleted
Group3 30 uncompleted
Group4  0 uncompleted
Group5  0 uncompleted

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:2)

你走在正确的轨道上。 GROUP BY该群组,但不是计算群组ID,而是尝试对不完整的任务执行SUM,如下所示:

SELECT g.id, g.name,
SUM(IF(t.status = 0, 1, 0)) incomplete_tasks
FROM task_groups g
LEFT JOIN tasks t ON (t.group_id = g.id)
GROUP BY g.id ASC
HAVING incomplete_tasks > 0;

如果要列出所有任务组,请忽略HAVING子句。

注意:我在查询中没有看到g.status的目的,并且status未在groups表中列为列,所以我已经离开了我的例子。