2011-02-13 159 views
1

我有一個查詢如何連接一列的值,如果其他列具有相同的價值

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      | 
+------------+--------------------------------+------------------------------+ 

也就是說,我希望它合併297的contact_type

這可能嗎?有人能告訴我如何? :)

感謝

回答

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 
+0

超強!謝謝! ;) – Obay

相關問題