Home > Enterprise >  Join to table and if no match join to another table
Join to table and if no match join to another table

Time:01-08

I need to join to a table and if no matches join to another table.

Main Table - A

Id Code DataId
1 testa 123
2 testb 456

Table - B

Idb Code DataId
22 testa 123

Table - C

Idb Code DataId
33 testb 456

In my sample data above I would need result set to be:

Id Code DataId Idb
1 testa 123 22
2 testb 456 33

I've tried left joining Table A to Table B. This gives me a null DataId for the 2nd record - understandably. I could do another left join to Table C. Is that the right approach? Or is joining to a table and if no matches join to another table viable?

CodePudding user response:

I'd left join on both tables and coalesce the idb columns:

SELECT    a.*, COALESCE(b.idb, c.idb)
FROM      a
LEFT JOIN b ON a.code = b.code
LEFT JOIN c ON a.code = c.code

CodePudding user response:

in case you want to return match records you can use the INNER JOIN SQL statement it will dynamically look for match rows between given tables and return the match records like below's peace of codes:

SELECT *
FROM `table_a`
INNER JOIN `table_b` ON table_a.code = table_b.code
INNER JOIN `table_c` ON table_a.code = table_c.code 
  • Related