使用联接表中的两个计数编写JOIN查询

时间:2012-11-24 18:24:50

标签: mysql sql

我已经花了几个小时与之斗争,但我无法让计数得以实现。希望有人能帮忙吗?!

我有一个项目表和任务表,链接在project_id上。我可以使用下面的查询获取project_id,project_name和status_id:

SELECT 
    a.project_id, 
    a.project_name,
    b.status_id
FROM project_list as a
INNER JOIN task_list as b
ON a.project_id=b.project_id

我想为每个项目选择一条记录,并根据status_id添加两个计数字段。在伪代码中:

SELECT 
    a.project_id, 
    a.project_name,
    (SELECT COUNT(*) FROM task_list WHERE status_id < 3) as not_completed,
    (SELECT COUNT(*) FROM task_list WHERE status_id = 3) as completed
FROM project_list as a
INNER JOIN task_list as b
ON a.project_id=b.project_id
GROUP BY project_id

我的创建表脚本如下:

CREATE TABLE `project_list` (
  `project_id` int(11) NOT NULL AUTO_INCREMENT,
  `topic_id` int(11) DEFAULT NULL,
  `project_name` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`project_id`)
)

CREATE TABLE `task_list` (
  `task_id` int(11) NOT NULL AUTO_INCREMENT,
  `project_id` int(11) DEFAULT NULL,
  `task_name` varchar(45) DEFAULT NULL,
  `status_id` int(11) DEFAULT '0',
  PRIMARY KEY (`task_id`)
)

非常感谢任何帮助。谢谢!

编辑:答案:

SELECT 
    a.project_id, 
    project_name,
    SUM(status_id != 3) AS not_completed,
    SUM(status_id = 3) AS completed,
    SUM(status_id IS NOT NULL) as total
FROM tasks.project_list as a
INNER JOIN tasks.task_list as b
ON a.project_id=b.project_id
GROUP BY a.project_id

1 个答案:

答案 0 :(得分:4)

问题在于,在子查询中,您要计算整个表中的所有行,而不仅仅是具有正确project_id的行。您可以通过修改每个子查询中的WHERE子句来解决此问题。

(SELECT COUNT(*)
 FROM task_list AS c
 WHERE c.status_id < 3
 AND a.project_id = c.project_id)

然而,更简单的方法是使用带有布尔条件的SUM而不是COUNT来计算与条件匹配的行:

SELECT 
    a.project_id, 
    a.project_name,
    SUM(b.status_id < 3) AS not_completed,
    SUM(b.status_id = 3) AS completed,
FROM project_list as a
INNER JOIN task_list as b
ON a.project_id = b.project_id
GROUP BY project_id

这是有效的,因为TRUE评估为1FALSE评估为0