MYSQL - 连接三个表

MYSQL - Joining three tables

我三个table排列如下

Person               Activity               Person_Activity
-------------------  --------------------   -----------------------------
ID | Name | Dept     ID | Activity | Type   PersonId | ActivityId | Value
-------------------  --------------------   -----------------------------
1    David  2        1   act1        1      2         1             5
2    Jim    1        2   act2        2      2         2             1 
3    Steve  1        3   act3        1      3         3             3
                                            1         1             1

我想 select Activity 类型 1 的部门 1 中所有人员的值。当 Person_Activity 中有值时,这很容易,但是当有是不是我仍然需要那个人的列表并且 activity 值为 0。EG.

PersonName | ActivityName | Value
Jim          act1           5
Jim          act3           0
Steve        act1           0
Steve        act3           3    

我已经尝试从 Person_activity table selecting 并使用右连接来连接 person 和 activity 但这对我不起作用。谁能指出正确的方向。

SELECT p.Name, a.Name, CASE WHEN (pa.Value IS NOT NULL) THEN pa.Value ELSE 0 END
FROM Person p
CROSS JOIN Activity a 
LEFT JOIN Person_Activity pa ON p.ID = pa.PersonId AND a.ID = pa.ActivityId
WHERE p.Dept = 1 and a.Dept = 1
ORDER BY 1, 2

并采样 fiddle 进行尝试:http://sqlfiddle.com/#!2/03d8b/2

为什么要使用 CROSSJOIN?为什么在 p.Dept 和 a.Dept 相同时同时进行过滤?

这个更简单

http://sqlfiddle.com/#!2/9c6537/3

SELECT p.Name, a.Activity, CASE WHEN (pa.Value is null) THEN 0 else pa.Value END
from Person p
left join Activity a on a.Type = p.Dept
left join Person_Activity pa on pa.PersonId = p.Id and pa.ActivityId = a.Id
where p.Dept = 1 and a.Type = 1
order by p.Name, a.Activity

如果 a.Type 字段与 p.Dept 字段不同,这是解决方案:

http://sqlfiddle.com/#!2/9c6537/5

SELECT p.Name, a.Activity, CASE WHEN (pa.Value is null) THEN 0 else pa.Value END
from Person p
left join Activity a on a.Type = 1
left join Person_Activity pa on pa.PersonId = p.Id and pa.ActivityId = a.Id
where p.Dept = 1 
order by p.Name, a.Activity