SQLite 在同一个表上左连接两次

发布于 2024-12-03 19:18:07 字数 557 浏览 1 评论 0原文

我有一个表,其中有几列包含另一个表的 ID。 示例:

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

因此,p1p2p3 是来自 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

北音执念 2024-12-10 19:18:07

是的,这是正确的做法。如果您知道 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

您可能需要查看 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:

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文