我有一个查询
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。
这可能吗?有人可以告诉我怎么样? :)
由于
答案 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