MySQL查询从多个表中选择并插入一个

时间:2016-01-27 11:16:13

标签: mysql sql

有5个表:A,B,C,D,E。 让每个表都包含一个“电子邮件”字段。 现在我们想要插入A中的所有电子邮件,这些电子邮件存在于C,D,E中,但不存在于B中。

示例查询:

CREATE TABLE a (email VARCHAR(100));
CREATE TABLE b (email VARCHAR(100));
CREATE TABLE c (email VARCHAR(100));
CREATE TABLE d (email VARCHAR(100));
CREATE TABLE e (email VARCHAR(100));

INSERT INTO b (email) VALUES ('a@b.com'), ('c@d.com');
INSERT INTO c (email) VALUES ('a@b.com'), ('e@f.com'), ('e@f.com');
INSERT INTO d (email) VALUES ('a@b.com'), ('c@d.com'), ('g@h.com');
INSERT INTO e (email) VALUES ('c@d.com'), ('g@h.com'), ('i@j.com'), ('i@j.com');

这就是我的尝试:

INSERT INTO a (email)
SELECT
c.email
FROM
c
LEFT JOIN b ON c.email = b.email
WHERE b.email IS NULL
UNION DISTINCT
SELECT
d.email
FROM
d
LEFT JOIN b ON d.email = b.email
WHERE b.email
UNION DISTINCT
SELECT
e.email as email
FROM
e
LEFT JOIN b ON e.email = b.email
WHERE b.email IS NULL;

2 个答案:

答案 0 :(得分:1)

联合来自C,D和E的所有电子邮件,然后丢弃B中不存在的结果:

INSERT INTO a (email)
select * from 
(
    SELECT c.email FROM c
    UNION 
    SELECT d.email FROM d
    UNION 
    SELECT e.email FROM e
) as p where p.email not in ( select email from b);

答案 1 :(得分:1)

以下几乎是您的描述的直接翻译:

insert into a(email)
    select email
    from ((select email from c) union
          (select email from d) union
          (select email from e)
         ) cde
    where not exists (select 1 from b where b.email = cde.email);

注意:这有意使用union删除重复项。如果您知道cde中没有重复项,或者您需要重复项,请改用union all