2016-11-13 29 views
0

您好我有一個表稱爲工程師和一張桌子稱爲Post_CodesMYSQL多組的毗連

當我使用下面的SQL,我得到工程師的列表,並通過使用組的毗連聲明與其相關聯的郵政編碼,但我不能弄清楚如何在另一個Group Concat中包含如何在另一個名爲Secondary_Post_Codes_Assigned的字段中列出通過Secondary_Engineer_id字段鏈接到同一個工程師的那些郵編。

SELECT 
    Engineer.Engineer,GROUP_CONCAT(Post_Code SEPARATOR ', ') as Post_Codes_Assigned, 
    Engineer.Region, 
    Engineer.active, 
    Engineer.Engineer_id 
FROM Engineer INNER JOIN Post_Code ON Engineer.Engineer_id = Post_Code.Engineer_id 
GROUP BY Engineer_id 

我需要的是與此類似的輸出。

Engineer_id | Post_Codes_Assigned | Secondary_Post_Codes_Assigned 


---------- 
1   | AW, AW3    | B12       | 
2   | B12     | AW, CV12      |     

我希望這很清晰,因爲我對mysql很新。

問候 艾倫

+1

您目前的查詢已經有幾個問題。你能向我們展示樣本數據嗎? –

+0

@Tim Biegeleisen:有幾個問題?哪一個?你是否指'GROUP BY Engineer_id'中缺少的限定符?我必須承認我沒有看到其他人。 –

+0

一般來說,最好處理表示層中的數據顯示問題。 – Strawberry

回答

0

您已經加入後一次代碼,並列出他們現在做的與次級的人一樣。

SELECT 
    e.Engineer, 
    GROUP_CONCAT(DISTINCT pc1.Post_Code) AS Primary_Post_Codes_Assigned, 
    GROUP_CONCAT(DISTINCT pc2.Post_Code) AS Secondary_Post_Codes_Assigned, 
    e.Region, 
    e.active, 
    e.Engineer_id 
FROM Engineer e 
JOIN Post_Code pc1 ON e.Engineer_id = pc1.Engineer_id 
JOIN Post_Code pc2 ON e.Engineer_id = pc2.Secondary_Engineer_id 
GROUP BY e.Engineer_id; 

正如你看到的,你需要DISTINCT因爲選擇所有小學和所有中學郵政編碼時,你得到的行中的中間結果他們的所有組合。所以你必須擺脫重複。出於這個原因,ist在加入之前最好聚合。 (我一般認爲是個好主意,所以你可能要與聚集工作時,使之成爲一個習慣。)

SELECT 
    e.Engineer, 
    pc1.Post_Codes AS Primary_Post_Codes_Assigned, 
    pc2.Post_Codes AS Secondary_Post_Codes_Assigned, 
    e.Region, 
    e.active, 
    e.Engineer_id 
FROM Engineer e 
JOIN 
(
    SELECT Engineer_id, GROUP_CONCAT(Post_Code) AS Post_Codes 
    FROM Post_Code 
    GROUP BY Engineer_id 
) pc1 ON e.Engineer_id = pc1.Engineer_id 
JOIN 
(
    SELECT Secondary_Engineer_id, GROUP_CONCAT(Post_Code) AS Post_Codes 
    FROM Post_Code 
    GROUP BY Secondary_Engineer_id 
) pc2 ON e.Engineer_id = pc2.Secondary_Engineer_id; 

第三個選擇是SELECT子句中的子查詢。我通常更喜歡它們在FROM子句中,因爲這樣子很容易在子查詢中添加更多的列,這在SELECT子句中是不可能的。

SELECT 
    e.Engineer, 
    (
    SELECT GROUP_CONCAT(pc1.Post_Code) 
    FROM Post_Code pc1 
    WHERE pc1.Engineer_id = e.Engineer_id 
) AS Primary_Post_Codes_Assigned, 
    (
    SELECT GROUP_CONCAT(pc2.Post_Code) 
    FROM Post_Code pc2 
    WHERE pc2.Secondary_Engineer_id = e.Engineer_id 
) AS Secondary_Post_Codes_Assigned, 
    e.Region, 
    e.active, 
    e.Engineer_id 
FROM Engineer e; 
+0

非常感謝,這非常棒。 –