mysql - 如何避免同一个表上的多个 JOINS?

标签 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

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

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/

相关文章:

sql - 查询具有多个子实体的 XML

mysql - 海量数据关联各种表格的常用方法

php - 从 PHP 和 MySQL 中的 2 列创建关联数组

php - MYSQL - 从标签搜索中仅检索完整单词

php - 我的 php 生成的电子邮件没有显示我数据库中的所有记录

sql - 具有名称和最接近的富裕祖先的行

javascript - 使用ajax从函数重新加载php数据

mysql - 将 SELECT 中的相关子查询重写为 JOIN 语句

database - 你能在基于复制的分布式数据库中删除吗?

sql - 跨多个表添加序列值