为什么将多行组合到一列中会复制数据?

时间:2017-09-29 06:19:04

标签: mysql sql join group-concat

我知道这个问题之前已经得到了回答,但我找不到有类似问题的问题。

我在下面创建了一个示例表:

TableA - aID | aName
          1  | House


TableB - bID | bmodel    | bname  | aID
          1  | studio    | classy |  1
          2  | studio    | small  |  1
          3  | apartment | classy |  1

TableC - cID | cmodel   | cname  | aID
          1  | bedroom  | big    | 1
          2  | bedroom  | small  | 1
          3  | bedroom  | big    | 1

我试图实现

aID | aName |          bmodel bname                            |     cmodel cname
 1  | house | studio classy, studio small, apartment classy    | bed big, bed small, bed big

这里发生了什么

aID | aName |          bmodel bname                                                                          |     cmodel cname
 1  | house | studio classy, studio small, apartment classy, studio classy, studio small, appartment classy  | bedroom big, bedroom small, bedroom small, bedroom big, bedroom small, bedroom small

我添加的GROUP_CONCAT就更多了。

我使用的代码:

SELECT 
    TableA.aId, TableA.aname,
    GROUP_CONCAT(CONCAT(TableB.bmodel, ' ', TableB.bname) SEPARATOR ', ') as BModNam,
    GROUP_CONCAT(CONCAT(TableC.cmodel, ' ', TableC.cname) SEPARATOR ', ') AS CModNam

FROM TableB
    JOIN cases
        ON TableB.aID = TableA.aId
    JOIN TableC
        ON TableC.aid = TableA.aID

WHERE
    TableA.aID=1

我知道我可以使用distinct但会排除有重复的行(即工作室,经典,卧室,大)

1 个答案:

答案 0 :(得分:1)

在select语句中调用GROUP_CONCAT作为子查询:

SELECT
    aID,
    aName,
    (SELECT GROUP_CONCAT(CONCAT(b.bmodel, ' ', b.bname))
     FROM TableB b WHERE b.aID = t.aID GROUP BY b.aID) AS bmodel_bname,
    (SELECT GROUP_CONCAT(CONCAT(c.cmodel, ' ', c.cname))
     FROM TableC c WHERE c.aID = t.aID GROUP BY c.aID) AS cmodel_cname
FROM TableA t
WHERE aID = 1;

加入和当前输出的问题在于,您将两个表中的模型和名称组相乘。使用子查询可以解决这个问题,因为每个子查询只为该表生成一个聚焦的CSV列表。

<强>输出:

aID aName   bmodel_bname                  cmodel_cname
1   House   studio classy,studio small,   bedroom big,bedroom small,
            apartment classy              bathroom big

Demo