SQLite 在同一个表上左连接两次
我有一个表,其中有几列包含另一个表的 ID。 示例:
T1 {id,p1,p2,p3}
T2 {id,name}
因此,p1
、p2
和 p3
是来自 T2
的 ID。 我想要做的是从 T1
中选择所有内容,并从 T2
中选择名称值。
这就是我现在正在使用的:
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;
应该这样做吗?我应该担心任何速度问题吗?
谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,这是正确的做法。如果您知道
T2
将具有所有正确的值,那么您可以使用内部联接而不是外部联接:您可能需要查看
T1
列的外键,以确保您在T2
中拥有所需的一切。性能应该很好,这是一个非常标准的查询。
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:You might want to have a look at foreign keys for the
T1
columns to ensure that you do have everything you need inT2
.The performance should be fine, that's a pretty standard query.