如何在同一个表上避免多个JOINS?

时间:2014-08-02 19:11:05

标签: mysql sql database-design

存在两个表,例如:

GROUPS
id team1_id team2_id
1     1       2
2     3       1

TEAMS
id  name
1   aaa
2   bbb
3   ccc

我需要获取该组中的团队名称。因此,查询看起来像这样,它可以工作,但由于Team表的多个连接,它相对较慢。

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支球队。

2 个答案:

答案 0 :(得分:0)

你可以看看这是否表现更好 - (使用一个连接,但该表上的联合)

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

小提琴: 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

小提琴: http://sqlfiddle.com/#!2/3ba95c/10/0

答案 1 :(得分:0)

你可以像这样使用每两个id加两个:

SELECT id1, name1, name2 FROM 
  (SELECT Groups.id AS id1, Groups.team1_id as tid1, Teams.name as name1  FROM Groups LEFT JOIN Teams ON Groups.team1_id = Teams.id) AS S1,
  (SELECT Groups.id AS id2, Groups.team2_id as tid2, Teams.name as name2  FROM Groups LEFT JOIN Teams ON Groups.team2_id = Teams.id) AS S2
  WHERE id1=id2
  ORDER BY id1

实施例: http://sqlfiddle.com/#!9/2952af/2