There are 5 tables: A, B, C, D, E. Let each table contain an 'email' field. Now we want to INSERT all the emails in A which is present in any of C, D, E but NOT in B.
Sample queries:
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 ('[email protected]'), ('[email protected]');
INSERT INTO c (email) VALUES ('[email protected]'), ('[email protected]'), ('[email protected]');
INSERT INTO d (email) VALUES ('[email protected]'), ('[email protected]'), ('[email protected]');
INSERT INTO e (email) VALUES ('[email protected]'), ('[email protected]'), ('[email protected]'), ('[email protected]');
This is what I tried:
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;