MySQL - INSERT INTO ... SELECT ... UNION I'm having an issue with a fairly complex query where I need to store the ids from one table (based on heavy criteria) into a narrow, alternate table for future reference, but I keep running into a bad sql construct error.

If I run the following query by itself it works fine:

(SELECT DISTINCT a.id FROM accounts AS a
WHERE a.createdate &gt;= date_sub(now(), INTERVAL 1 YEAR)
AND a.email NOT LIKE '%gmail.com')
UNION DISTINCT
(SELECT DISTINCT a.id FROM accounts AS a
WHERE a.createdate &lt; date_sub(now(), INTERVAL 1 YEAR)
AND a.email NOT LIKE '%yahoo.com') AND a.email NOT IN
(SELECT email FROM inactive_clients));


However, if I try to run same query with like this:

INSERT INTO my_backup_table (account_id) VALUES ($aboveQuery);


I get the following error:

MySQL server version for the right syntax to use near 'UNION DISTINCT (SELECT DISTINCT a.id FROM accounts at line 1


I tried any number of parenthetical permutations and still received the same error.
You cannot use the INSERT INTO tblname (...) VALUES ... syntax

You must use the INSERT INTO tblname (...) SELECT ... syntax

Try the Following:

INSERT INTO my_backup_table (account_id)
SELECT id FROM
(
    (SELECT DISTINCT a.id FROM accounts AS a
    WHERE a.createdate &gt;= date_sub(now(), INTERVAL 1 YEAR)
    AND a.email NOT LIKE '%gmail.com')
    UNION DISTINCT
    (SELECT DISTINCT a.id FROM accounts AS a
    WHERE a.createdate &lt; date_sub(now(), INTERVAL 1 YEAR)
    AND a.email NOT LIKE '%yahoo.com') AND a.email NOT IN
    (SELECT email FROM inactive_clients))
) A;