简体   繁体   中英

SQLite left joining twice on the same table

I have a table that has a few columns that contain IDs to one other table. Example:

T1 {id,p1,p2,p3}
T2 {id,name}

So, p1 , p2 and p3 are IDs from T2 . What I want to do is select all from T1 and have the name value from T2 as well.

This is what I am using now:

select
     T1.id,T1.p1,T1.p2,T1.p3,
     T2a.name as p1_name,T2b.name as p2_name,T2c.name as p3_name
from
     T1 left join T2 as T2a on T1.p1=T2a.id
     left join T2 as T2b on T1.p2=T2b.id
     left join T2 as T2c on T1.p3=T2c.id;

Is that how this should be done? Are there any speed issues I should be worried about?

Thank you.

Yes, that's the right way to do it. If you know that T2 will have all the right values then you could use inner joins instead of outer joins:

select T1.id,
       T1.p1, T21.name as p1_name,
       T1.p2, T22.name as p2_name,
       T1.p3, T23.name as p3_name
from T1
join T2 as T21 on T1.p1 = T21.id,
join T2 as T22 on T1.p2 = T22.id,
join T2 as T23 on T1.p3 = T23.id

You might want to have a look at foreign keys for the T1 columns to ensure that you do have everything you need in T2 .

The performance should be fine, that's a pretty standard query.

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