[英]How to avoid multiple joining the same table?
團體
id team1_id team2_id
1 1 2
2 3 1
團隊
id name
1 aaa
2 bbb
3 ccc
是否可以在不更改架構的情況下避免多重連接,或者必須更改架構才能改善這一點? 每組只會有 2 支球隊。
預期的:
id team1_name team2_name
1 aaa bbb
2 ccc aaa
避免多重連接的一種方法是進行條件聚合:
select
g.id,
max(case when t.id = g.team1_id then t.name end) team1_name,
max(case when t.id = g.team2_id then t.name end) team2_name
from groups g
inner join teams t on t.id in (g.team1_id, g.team2_id)
group by g.id
雖然如果將新列添加到groups
表中,這可以更輕松地擴展查詢,但實際上並不能保證比連接解決方案的性能更好。 這將取決於您的數據分布。 如果性能對您很重要,您將需要針對您的真實數據測試這兩種解決方案。
與連接解決方案的另一個主要區別是,此查詢實際上並不能確保作為組表一部分的teams
ID 在groups
表中都可用(您需要添加一個having
子句來實現它)。 根據您的用例,這可能是您想要的,也可能不是您想要的。
試試這個
Select id, max(case when
g.id=t.team1_id then
g.name end),
max(case when
g.id=t.team2_id then
g.name end)
From groups g right join
Teams t on
g.id=t.id
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.