[英]SQL LEFT JOIN to table determied by result from inner SELECT
I'm just wondering if this is possible.我只是想知道这是否可能。 I'm trying show all results from one table and grab more details from respective group(table)
我正在尝试显示一张表中的所有结果并从各个组(表)中获取更多详细信息
+--------------------------+ +--------------------------+
| table group_a | | table group_b |
+--------------------------+ +--------------------------+
| id name age | | id name age |
| s01 John 10 | | s11 Clark 11 |
| s02 Jane 11 | | s12 Cherry 09 |
+--------------------------+ +--------------------------+
+----------------------------+
| table result_1 |
+----------------------------+
| id result group |
| s01 9 a |
| s12 10 b |
| s11 9 b |
| s02 7 a |
+----------------------------+
I was hoping to get this output我希望得到这个 output
id name age result
+------------------------------------+
s12 Cherry 09 10
s01 John 10 9
s11 Clark 11 9
s02 Jane 11 7
I'm kind of stuck on how to point my query to different tables.我有点坚持如何将我的查询指向不同的表。 Anyway I just want to know if this is possible or I should go for different approach.
无论如何,我只是想知道这是否可能,或者我应该使用 go 来采用不同的方法。
B'rgrds, B'rgrds,
You can use left join
twice:您可以使用两次
left join
:
select r.id, coalesce(a.name, b.name) as name, coalesce(a.age, b.age) as age,
r.result
from result_1 r left join
group_a a
on r.group = 'a' and r.id = a.id left join
group_b b
on r.group = 'b' and r.id = b.id;
I would expect the above to have the better performance, but you can also use union all
before the join:我希望上述内容具有更好的性能,但您也可以在加入之前使用
union all
:
select r.id, ab.name, ab.age, r.result
from result_1 r left join
((select id, name, age, 'a' as group
from group_a a
) union all
(select id, name, age, 'b' as group
from group_b b
)
) ab
on r.group = ab.group and r.id = as.id ;
Note: It is better to have all the groups in a single table rather than splitting them among multiple tables.注意:最好将所有组放在一个表中,而不是将它们拆分到多个表中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.