patternsqlMinor
MySQL - INSERT INTO ... SELECT ... UNION
Viewed 0 times
insertintounionmysqlselect
Problem
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:
However, if I try to run same query with like this:
I get the following error:
I tried any number of parenthetical permutations and still received the same error.
If I run the following query by itself it works fine:
(SELECT DISTINCT a.id FROM accounts AS a
WHERE a.createdate >= 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 < 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 1I tried any number of parenthetical permutations and still received the same error.
Solution
You cannot use the
You must use the
Try the Following:
INSERT INTO tblname (...) VALUES ... syntaxYou must use the
INSERT INTO tblname (...) SELECT ... syntaxTry the Following:
INSERT INTO my_backup_table (account_id)
SELECT id FROM
(
(SELECT DISTINCT a.id FROM accounts AS a
WHERE a.createdate >= 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 < date_sub(now(), INTERVAL 1 YEAR)
AND a.email NOT LIKE '%yahoo.com') AND a.email NOT IN
(SELECT email FROM inactive_clients))
) A;Code Snippets
INSERT INTO my_backup_table (account_id)
SELECT id FROM
(
(SELECT DISTINCT a.id FROM accounts AS a
WHERE a.createdate >= 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 < date_sub(now(), INTERVAL 1 YEAR)
AND a.email NOT LIKE '%yahoo.com') AND a.email NOT IN
(SELECT email FROM inactive_clients))
) A;Context
StackExchange Database Administrators Q#20667, answer score: 6
Revisions (0)
No revisions yet.