您好我有一个名为Engineers的表和一个名为Post_Codes的表
当我使用下面的sql时,我通过使用Group Concat声明获得了工程师列表和与之关联的邮政编码,但我无法弄清楚如何在另一个Group Concat(如果确实需要一个)中也包含它也列出在名为Secondary_Post_Codes_的另一个字段中,通过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很新。
此致 艾伦
答案 0 :(得分:0)
您已加入主要邮政编码并列出它们,现在对辅助邮政编码进行同样的操作。
GetFiles
如您所见,您需要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
第三个选项是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