我有三个表格排列如下
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
我想为活动类型1的部门1中的所有人选择值。当Person_Activity中有值时,这很容易,但是当我没有时,我仍然需要列出该人员和值为0的活动.EG。
PersonName | ActivityName | Value
Jim act1 5
Jim act3 0
Steve act1 0
Steve act3 3
我尝试从Person_activity表中选择并使用正确的联接来加入人和活动但是这对我不起作用。任何人都可以指出正确的方向。
答案 0 :(得分:2)
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
并尝试小提琴试试:http://sqlfiddle.com/#!2/03d8b/2
答案 1 :(得分:1)
为什么要使用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