存在两个表,例如:
GROUPS
id team1_id team2_id
1 1 2
2 3 1
TEAMS
id name
1 aaa
2 bbb
3 ccc
我需要获取群组中的团队名称。因此,查询看起来像这样并且它可以工作,但由于团队表的多个联接,它相对较慢。
SELECT t1.name, t2.name
FROM Groups g
JOIN Teams t1 ON t1.id = g.team1_id
JOIN Teams t2 ON t2.id = g.team2_id
是否可以在不更改架构的情况下避免多重联接,或者必须更改架构才能改善这一点?每组只能有 2 支球队。
最佳答案
您可以看看这是否表现更好 - (使用一个连接,但在该表上使用联合)
select x.id, group_concat(t.name order by x.id) as team_names
from (select id, team1_id as team_id
from groups
union all
select id, team2_id
from groups) x
join teams t
on x.team_id = t.id
group by x.id
fiddle : http://sqlfiddle.com/#!2/3ba95c/4/0
或者,如果您绝对需要将每个团队放在单独的列中:
select id,
substring_index(team_names, ',', -1) as team1,
substring_index(team_names, ',', 1) as team2
from (select x.id, group_concat(t.name order by x.id) as team_names
from (select id, team1_id as team_id
from groups
union all
select id, team2_id
from groups) x
join teams t
on x.team_id = t.id
group by x.id) x
fiddle : http://sqlfiddle.com/#!2/3ba95c/10/0
关于mysql - 如何避免同一个表上的多个 JOINS?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25098483/