简体   繁体   中英

Mysql join 3 tables no rows merging

I'm trying to write a query to select some rows from 3 tables but I have some special needs.

So let say I have table1,table2,table3 as t1,t2,t3 t1 contains an id column, which is a foreign key in t2 and t3.

t1 content :

id 
1  

t2 content :

id fk val1
1  1  123
2  1  234 

t3 content :

id fk val2
1  1  345
2  1  456 

The result I'm trying to output is :

t2.id t3.id fk val1 val2
1     NULL  1  123  NULL
2     NULL  1  234  NULL 
NULL  1     1  NULL 345
NULL  2     1  NULL 456 

As of now, I went to this query, but my fk column is splitted in 2 columns.

SELECT * FROM t2 
LEFT JOIN t3 ON (FALSE) 
WHERE t2.Fk=1
UNION ALL 
SELECT * FROM t2 
RIGHT JOIN t3 ON (FALSE) 
WHERE t3.Fk=1

Any advice how ?

Use coalesce()

SELECT t2.id, t3.id, coalesce(t2.fk,t3,fk) as fk val1, val2 FROM t2 
LEFT JOIN t3 ON (FALSE) 
WHERE t2.Fk=1
UNION ALL 
SELECT t2.id, t3.id, coalesce(t2.fk,t3,fk) as fk val1, val2 FROM t2 
RIGHT JOIN t3 ON (FALSE) 
WHERE t3.Fk=1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM