2014-12-29 233 views
1

我有一個聯繫表。每個聯繫人可以有多個不同或相同表格的電話號碼。同樣,每個聯繫人可以擁有多個具有不同或相同標籤的電子郵件我需要選擇所有不同的電話號碼和電子郵件ID屬於特定的聯繫人。MySQL group_concat加入

CREATE TABLE IF NOT EXISTS `contact` (
    `id` int(8) unsigned NOT NULL , 
    `fname` varchar(64) NOT NULL, 
    `lname` varchar(64) NOT NULL 
) ENGINE=InnoDB DEFAULT CHARSET=latin1 ; 
CREATE TABLE IF NOT EXISTS `phone` (
    `id` int(8) unsigned NOT NULL , 
    `sourceid` int(8) unsigned NOT NULL , 
    `type` varchar(16) NOT NULL, 
    `phone` varchar(16) NOT NULL 
) ENGINE=InnoDB DEFAULT CHARSET=latin1 ; 
CREATE TABLE IF NOT EXISTS `email` (
    `id` int(8) unsigned NOT NULL , 
    `sourceid` int(8) unsigned NOT NULL , 
    `type` varchar(16) NOT NULL, 
    `email` varchar(128) NOT NULL 
) ENGINE=InnoDB DEFAULT CHARSET=latin1 ; 

INSERT INTO contact values (1,'john'  ,'j'), 
(2, 'jose'  ,'f'), 
(3, 'test'  ,'k'), 
(4, 'tester'  ,'j'); 


INSERT INTO phone values(1 ,1, 'Home', '123456'), 
(2 ,1, 'Home', '123456342'), 
(3 ,1, 'Office', '12345645'), 
(4 ,1, 'Mobile', '1234567'), 
(5 ,2, 'Home', '123456'), 
(5 ,2, 'Home', '987556'); 

INSERT INTO email values 
(1 ,1, 'Home', '[email protected]'), 
(2 ,1, 'Home', '[email protected]'), 
(3 ,1, 'Office', '[email protected]'), 
(4 ,2, 'Home', '[email protected]'), 
(5 ,4, 'Home', '[email protected]'); 

我試圖GROUP_CONCAT但它具有標籤重複的條目。

SELECT C.id, fname, lname 
, GROUP_CONCAT(ph.sourceid), 
GROUP_CONCAT(em.sourceid), 
GROUP_CONCAT(ph.type), GROUP_CONCAT(ph.phone), 
GROUP_CONCAT(em.type), GROUP_CONCAT(em.email) 
FROM contact AS C 
LEFT JOIN phone AS PH ON PH.sourceid = C.id 
LEFT JOIN email EM ON EM.sourceid = C.id 
WHERE C.id='1' 
GROUP BY C.id 

SQL FIDDLE

回答

3

試試這個:

SELECT c.id, c.fname, c.lname, 
     ph.PhoneType, ph.PhoneNos, 
     em.EmailType, em.EmailIds 
FROM contact AS c 
LEFT JOIN (SELECT ph.sourceid, GROUP_CONCAT(ph.type) AS PhoneType, GROUP_CONCAT(ph.phone) AS PhoneNos 
      FROM phone AS ph 
      GROUP BY ph.sourceid 
     ) AS ph ON ph.sourceid = c.id 
LEFT JOIN (SELECT em.sourceid, GROUP_CONCAT(em.type) AS EmailType, GROUP_CONCAT(em.email) AS EmailIds 
      FROM email AS em 
      GROUP BY em.sourceid 
     ) AS em ON em.sourceid = c.id 
WHERE c.id = '1' 
GROUP BY c.id 

檢查

輸出

| ID | FNAME | LNAME |    PHONETYPE |       PHONENOS |  EMAILTYPE |         EMAILIDS | 
|----|-------|-------|-------------------------|-----------------------------------|------------------|--------------------------------------------| 
| 1 | john |  j | Home,Home,Office,Mobile | 123456,123456342,12345645,1234567 | Home,Home,Office | [email protected],[email protected],[email protected] | 
+0

小號奧利,我忘了提到我也需要標籤(類型)。如果我添加DISTINCT,則不會選擇不同的標籤。 – Damodaran

+0

SELECT C.id,fname,lname,GROUP_CONCAT(DISTINCT ph.phone),GROUP_CONCAT(DISTINCT em.email) ,GROUP_CONCAT(DISTINCT em.type) FROM contact AS C LEFT JOIN phone AS PH ON PH.sourceid = C.id LEFT JOIN電子郵件作爲他們了EM.sourceid = C.id WHERE C.id =「1」 GROUP BY C.id 這將返回的電子郵件類型家庭和辦公室,但有兩個家庭型態表中的電子郵件 – Damodaran

+0

太好了。謝謝。 – Damodaran