6

我试图在一个字符串中加入两个多对多关联。在此示例中,每个团队都有未确定数量的颜色和未确定数量的获奖者。

这是架构:

在此处输入图像描述

这是我正在使用的查询:

SELECT
    teams.name AS name,
    GROUP_CONCAT(colours.name) AS colours,
    GROUP_CONCAT(awards.name) AS awards
FROM
    teams

-- join colours
INNER JOIN teams_to_colours
        ON teams.id = teams_to_colours.team_id

INNER JOIN colours
        ON teams_to_colours.colour_id = colours.id

-- join awards
INNER JOIN teams_to_awards
        ON teams.id = teams_to_awards.team_id

INNER JOIN awards
        ON teams_to_awards.award_id = awards.id

WHERE
    teams.name="A-Team"

GROUP BY
    teams.id

问题是颜色和奖项会重复。假设 A-Team 有红色和蓝色作为颜色,作为奖项 TrollAward 和 DarwinAward ......我从 SQL 得到的结果如下所示:

name: "A-Team"
colours: "red,blue,red,blue"
awards: "TrollAward,DarwinAward,TrollAward,DarwinAward"

我试图只加入一个多对多,并且工作得很好,所以我想我正在监督多个加入的东西......

4

1 回答 1

4

DISTINCT快速而肮脏的答案是添加GROUP_CONCAT()功能:

SELECT
    teams.name AS name,
    GROUP_CONCAT(DISTINCT colours.name) AS colours,
    GROUP_CONCAT(DISTINCT awards.name) AS awards
...

尽管对于大桌子,这可能不是很有效。第二种方法是GROUP BY在两个子查询(派生表)中,您从awards一个和colurs另一个中获取连接,然后连接这些派生表。

于 2013-06-20T08:06:55.613 回答