我使用此sql有重复的记录:
SELECT emp.id, first_name, second_name, last_name, department, positions,
GROUP_CONCAT(email, " ", email_type SEPARATOR " || ") AS mails,
GROUP_CONCAT(number, " ", number_type SEPARATOR " || ") AS numbers
FROM geography.employee AS emp
INNER JOIN geography.employee_email AS ee ON emp.id = ee.email_FK
LEFT JOIN geography.employee_number AS en ON emp.id = en.number_FK
WHERE first_name = 'John' AND last_name = 'Ausini'
GROUP BY emp.id
所以我得到了邮件的这些结果:
heyhey@abv.bg personal || heyhey@abv.bg personal || summer_geals@bwtc.co work || summer_geals@bwtc.co work || ivanov@abv.bg personal || ivanov@abv.bg personal
和数字:
+7654656656565 work || +7654656465655 personal || +7654656656565 work || +7654656465655 personal || +7654656656565 work || +7654656465655 personal
奇怪的是,在我的第二条记录中,邮件没有重复,邮件:
hei@abv.bg personal || hurei@abv.bg personal || burei@abv.bg personal || work@bwtc.com work
...但是在此记录中,我没有数字,也许这与前一个数字有所不同。 我的预期输出不会像这样对每个记录重复数据(对于第一个记录示例):
heyhey@abv.bg personal || summer_geals@bwtc.co work || ivanov@abv.bg personal
...也没有数字重复。 DISTINCT也不起作用(如果我把它放在SELECT之后),尽管我不喜欢掩盖问题,但我还是尝试了。
我在表中的数据:
答案 0 :(得分:2)
MySQL GROUP_CONCAT
允许您指定DISTINCT
,它应在串联前消除重复项:
SELECT
emp.id, first_name, second_name, last_name, department, positions,
GROUP_CONCAT(DISTINCT email, " ", email_type SEPARATOR " || ") AS mails,
GROUP_CONCAT(DISTINCT number, " ", number_type SEPARATOR " || ") AS numbers
FROM geography.employee AS emp
INNER JOIN geography.employee_email AS ee ON emp.id = ee.email_FK
LEFT JOIN geography.employee_number AS en ON emp.id = en.number_FK
WHERE first_name = 'John' AND last_name = 'Ausini'
GROUP BY emp.id
答案 1 :(得分:2)
由于您仅获得单个用户的信息,因此我会推荐Salman A的答案;但是如果您要使用多个(或全部)用户,而用户往往会有很多电子邮件和电话号码,则此版本可能会更快。
SELECT emp.id, first_name, second_name, last_name, department, positions, ee.mails, en.numbers
FROM geography.employee AS emp
INNER JOIN (SELECT email_FK, GROUP_CONCAT(email, " ", email_type SEPARATOR " || ") AS mails
FROM geography.employee_email
GROUP BY email_FK
) AS ee ON emp.id = ee.email_FK
LEFT JOIN (SELECT number_FK, GROUP_CONCAT(number, " ", number_type SEPARATOR " || ") AS numbers
FROM geography.employee_number
GROUP BY number_FK
) AS en ON emp.id = en.number_FK
;