简体   繁体   中英

How to join these tables safely?

I have a table Table1 . My application code reads from Table1 like this:

Select id, table2_id, table3_id from Table1

I would like it to also return values name from tables Table2 and Table3 by changing my query like this:

select t1.id, t1.table2_id, t1.table3_id, t2.name, t3.name
from table1 t1
left outer join table2 t2 on t1.table2_id = t2.id
left outer join table3 t3 on t1.table3_id = t3.id

However, I don't want to change the behavior of the original query, which returns 1 result per row in Table1 .

I believe my changes to the query are safe because they t2.id and t3.id are unique columns, so Table2 and Table3 will contain at most 1 record for each Table3 record. If I was to user inner join , this changes would not be safe, because my query would return no results if Table2 or Table3 happen to not contain the expected record.

For this scenario, are my changes safe and correct? Or is it necessary to write some subqueries to join on?

Your query looks safe:

select t1.id, t1.table2_id, t1.table3_id, t2.name, t3.name
from table1 t1 left join
     table2 t2 
     on t1.table2_id = t2.id left join
     table3 t3
     on t1.table3_id = t3.id;

You can also phrase this using correlated subqueries (or a lateral join):

select t1.*,
       (select t2.name from table2 t2 where t1.table2_id = t2.id) as t2_name,
       (select t2.name from table3 t3 where t1.table2_id = t3.id) as t3_name,
from table1 t1;

This is even more of a guarantee that there are no duplicates. If there were, the query would return an error.

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