簡體   English   中英

MySQL查詢從多個表中選擇並插入一個

[英]MySQL query to select from multiple table and insert in one

有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;

合並來自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);

以下內容幾乎是您的描述的直接翻譯:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM