如果其他列具有相同的值,如何连接列的值

时间:2011-02-13 16:15:08

标签: sql mysql

我有一个查询

SELECT
    cc.contact_id,
    cc.name,
    ct.name AS contact_type
FROM
    contacts AS c
    LEFT JOIN contact_companies AS cc ON c.contact_id = cc.contact_id
    LEFT JOIN contacts_to_types AS ctt ON cc.contact_id = ctt.contact_id
    LEFT JOIN contact_types AS ct ON ctt.contact_type_id = ct.contact_type_id
WHERE
     cc.name LIKE '%p%'
ORDER BY name, contact_id

返回:

+------------+--------------------------------+--------------+
| contact_id | name                           | contact_type |
+------------+--------------------------------+--------------+
|        297 | Primary Properties Corporation | Supplier     |
|        297 | Primary Properties Corporation | Prospect     |
|        297 | Primary Properties Corporation | Customer     |
|        298 | San Miguel Corporation         | Prospect     |
|        301 | Sulpicio Lines                 | Supplier     |
+------------+--------------------------------+--------------+

当我希望它返回时:

+------------+--------------------------------+------------------------------+
| contact_id | name                           | contact_type                 |
+------------+--------------------------------+------------------------------+
|        297 | Primary Properties Corporation | Supplier, Prospect, Customer |
|        298 | San Miguel Corporation         | Prospect                     |
|        301 | Sulpicio Lines                 | Supplier                     |
+------------+--------------------------------+------------------------------+

也就是说,我希望它能合并contact_type的297。

这可能吗?有人可以告诉我怎么样? :)

由于

1 个答案:

答案 0 :(得分:2)

使用GROUP_CONCAT()聚合函数

SELECT
    cc.contact_id,
    cc.name,
    GROUP_CONCAT(ct.name SEPARATOR ', ') AS contact_type
FROM
    contacts AS c
    LEFT JOIN contact_companies AS cc ON c.contact_id = cc.contact_id
    LEFT JOIN contacts_to_types AS ctt ON cc.contact_id = ctt.contact_id
    LEFT JOIN contact_types AS ct ON ctt.contact_type_id = ct.contact_type_id
WHERE
     cc.name LIKE '%p%'
GROUP BY cc.contact_id
ORDER BY name, contact_id