使用条件计算连接行的问题

时间:2009-09-10 15:17:21

标签: sql mysql join

我遇到一些MySQL问题,并从连接表中选择列数。我有一种感觉,这将需要一个子选择语句来获取我想要加入的行,而不是在我的主要文件中进行这种行为。

我正在尝试选择链接到某个用户的项目列表。我还想包括分配给该项目和该用户的任务计数(但只包括某个状态的任务)。

我几乎工作 - 这意味着根本没有。它只返回项目ID 1,而不是id 2.这是因为我的'tasks.status< 9'where子句。

任何帮助都会很棒。如果我需要解释其他任何内容,请告诉我。

+-------------------------+
| projects_to_users       |
+-----------+-------------+
+ user_id   | project_id  |
+-----------+-------------+
+ 1         | 1           |
+-----------+-------------+
+ 1         | 2           |
+-----------+-------------+


+-------------------------+
| projects                |
+--------------+----------+
+ project_id   | name     |
+--------------+----------+
+ 1            | Foo      |
+--------------+----------+
+ 2            | Bar      |
+--------------+----------+

+------------------------------------------------+
| tasks                                          |
+-----------+--------------+----------+----------+
+ task_id   | project_id   | status   | name     |
+-----------+--------------+----------+----------+
+ 1         | 1            | 1        | Do it    |
+-----------+--------------+----------+----------+
+ 2         | 1            | 1        | Do itt   |
+-----------+--------------+----------+----------+
+ 3         | 1            | 9        | Do not   |
+-----------+--------------+----------+----------+



SELECT count( tasks.task_id ) AS task_count, projects.*
FROM (projects)
LEFT JOIN tasks ON tasks.project_id = projects.project_id
LEFT JOIN projects_to_users ON projects.project_id=projects_to_users.project_id
WHERE tasks.status<9
AND tasks.assigned_user_id = '1'
AND projects_to_users.user_id = '1'
GROUP BY projects.project_id


RETURNS:

+--------------+--------------+--------+
+ task_count   | project_id   | name   |
+--------------+--------------+--------+
+ 2            | 1            | Foo    |
+--------------+--------------+--------+

SHOULD RETURN:

+--------------+--------------+--------+
+ task_count   | project_id   | name   |
+--------------+--------------+--------+
+ 2            | 1            | Foo    |
+--------------+--------------+--------+
+ 0            | 2            | Bar    |
+--------------+--------------+--------+

2 个答案:

答案 0 :(得分:2)

如果要显示每个项目,每个用户的任务计数,您还应该按projects_to_users.user_id字段进行分组。

此外,您没有看到零计数项目的原因是因为您的WHERE条件期望通过LEFT JOIN子句进行匹配。如果将WHERE标准移动到连接本身,这应该更适合您。

例如:

SELECT count( tasks.task_id ) AS task_count, 
       projects.*
FROM (projects)
LEFT JOIN tasks ON tasks.project_id = projects.project_id AND tasks.status < 9 AND tasks.assigned_user_id = '1'
LEFT JOIN projects_to_users ON projects.project_id=projects_to_users.project_id AND projects_to_users.user_id = '1'
GROUP BY projects.project_id

答案 1 :(得分:0)

为什么你不能这样做一个简单的连接:

select count(*) from projects_to_users inner join tasks on projects_to_users.project_id=tasks.project_id;