简体   繁体   English

SQLite在同一表上两次退出连接

[英]SQLite left joining twice on the same table

I have a table that has a few columns that contain IDs to one other table. 我有一张表,其中有几列,其中包含另一张表的ID。 Example: 例:

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

So, p1 , p2 and p3 are IDs from T2 . 因此, p1p2p3是来自T2 ID。 What I want to do is select all from T1 and have the name value from T2 as well. 我想做的是从T1选择所有内容,并从T2中也获得名称值。

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: 如果您知道T2将具有所有正确的值,则可以使用内部联接而不是外部联接:

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 . 您可能希望查看T1列的外键 ,以确保在T2确实拥有所需的一切。

The performance should be fine, that's a pretty standard query. 性能应该很好,这是一个非常标准的查询。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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