MySQL中具有字段连接的多个表上的完全外连接

时间:2012-10-18 13:59:58

标签: mysql sql join concatenation

我有四张桌子:actingwritingfilmtech

email         | skill
-----------------------
foo@bar.com   | acting
foo1@bar.com  | acting
foo2@bar.com  | acting
...           | ...

email         | skill
-----------------------
foo@bar.com   | writing
foo7@bar.com  | writing
foo8@bar.com  | writing
...           | ...

email         | skill
-----------------------
foo4@bar.com  | film
foo9@bar.com  | film
foo12@bar.com | film
...           | ...

email         | skill
-----------------------
foo3@bar.com  | tech
foo4@bar.com  | tech
foo7@bar.com  | tech
...           | ...

我想创建一个新表skills,以便包含每个电子邮件地址,并将与每个地址相关的技能连接到技能字段中。

email         | skill
-----------------------
foo@bar.com   | acting, writing
foo1@bar.com  | writing, film
foo2@bar.com  | acting, film, tech
...           | ...

我通过联盟进行了全外连接,但我似乎无法做到正确。

更新:我意识到这些表的设计有多糟糕。我正在使用上表从frankenstein遗留CRM迁移数据,我需要在新表中分隔逗号值,以便将它们导入到新的CRM中。

1 个答案:

答案 0 :(得分:3)

SELECT email, GROUP_CONCAT(skill ORDER BY skill) skill
FROM
(
    SELECT email, skill FROM acting
    UNION
    SELECT email, skill FROM writing
    UNION
    SELECT email, skill FROM film
    UNION
    SELECT email, skill FROM tech
) x
GROUP BY email

SQLFiddle Demo