gpt4 book ai didi

mysql - 如何使用中间表在 2 个表上应用外连接?

转载 作者:可可西里 更新时间:2023-11-01 07:35:49 26 4
gpt4 key购买 nike

table1 | id | value
--------------------
1 | john
2 | frank
3 | patel
4 | jim

table2 | id | value
--------------------
6 | steve
7 | tim
8 | sunny
9 | bhaskar

merged | tabid1 | tabid2
------------------------------
3 | 7
4 | 8

需要的输出:

    output  | tabid1 | tabval1 | tabid2 | tabval2
1 | john | NULL | NULL
2 | frank | NULL | NULL
3 | patel | 7 | tim
4 | jim | 8 | sunny
NULL | NULL | 6 | steve
NULL | NULL | 9 | bhaskar

我试过:

SELECT * 
FROM table1
LEFT JOIN merged m1 ON table1.id = m1.tabid1, merged m2
RIGHT JOIN table2 ON table2.id = m2.tabid2

但是它给出了 16 行而不是要求的 6 行

最佳答案

select table1.id,table1.value,table2.id,table2.value 
from table1 left join merged on table1.id=merged.tabid1
left join table2 on merged.tabid2=table2.id
union
select table1.id,table1.value,table2.id,table2.value
from table2 left join merged on table2.id=merged.tabid2
left join table1 on merged.tabid1=table1.id ;

或右连接:

SELECT * FROM 
table1 LEFT JOIN merged on table1.id=merged.tabid1
LEFT JOIN table2 ON merged.tabid2=table2.id
UNION
SELECT * FROM
table1 RIGHT JOIN merged on table1.id=merged.tabid1
RIGHT JOIN table2 ON merged.tabid2=table2.id WHERE table1.id IS NULL;

关于mysql - 如何使用中间表在 2 个表上应用外连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9090804/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com