![](/img/trans.png)
[英]Left outer join with select where value in right table does not return all rows from left
[英]Select value from left table and full join right table
这有点难以解释,但我会尽力而为:
假设我有表A:
event | task | ref_person
------+------+-----------
1 | 20 | 1
2 | 9 | 2
我有表B(包含person
):
id | name
---+-----
1 | foo
2 | bar
3 | jim
产生这种表的MySQL查询是什么样的:
event | task | person
------+------+-------
1 | 20 | foo
1 | NULL | bar
1 | NULL | jim
2 | NULL | foo
2 | 9 | bar
2 | NULL | jim
我当前的方法是使用RIGHT JOIN
,但这不会使事件与NULL值组合。
这就是我当前的语句:
SELECT
a.*,
b.name
FROM
a
RIGHT JOIN b
ON b.id = a.ref_person
ORDER BY
a.event,
b.name
sqlfiddle似乎下降了,一旦它再次上升,我就添加一个
您想要进行cross join
以获取所有行,然后进行case
逻辑以获取任务:
select a.event,
(case when a.ref_person = b.id then a.task end) as task,
b.name
from tablea a cross join
tableb b ;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.