[英]Select value from left table and full join right table
This is a bit difficult to explain, but I'll give my best: 这有点难以解释,但我会尽力而为:
Let's say, I have table A: 假设我有表A:
event | task | ref_person
------+------+-----------
1 | 20 | 1
2 | 9 | 2
And I have table B (containing person
): 我有表B(包含
person
):
id | name
---+-----
1 | foo
2 | bar
3 | jim
What does a MySQL-query look like, that produces this sort of table: 产生这种表的MySQL查询是什么样的:
event | task | person
------+------+-------
1 | 20 | foo
1 | NULL | bar
1 | NULL | jim
2 | NULL | foo
2 | 9 | bar
2 | NULL | jim
My current approach is by using a RIGHT JOIN
, but this won't get me the event combined with the NULL-value. 我当前的方法是使用
RIGHT JOIN
,但这不会使事件与NULL值组合。
This is what my current statement looks like: 这就是我当前的语句:
SELECT
a.*,
b.name
FROM
a
RIGHT JOIN b
ON b.id = a.ref_person
ORDER BY
a.event,
b.name
sqlfiddle seems down, I'll add one as soon as it's up again sqlfiddle似乎下降了,一旦它再次上升,我就添加一个
You want to do a cross join
to get all the rows, then case
logic to get the task: 您想要进行
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.