简体   繁体   中英

MySQL INSERT with SELECT UNION gives syntax error

Supposed I have a table SomeTable with a single INT column.

This query works fine:

INSERT INTO SomeTable
(SELECT 1 WHERE true) 
UNION
(SELECT 2 FROM SomeTable WHERE true) 

在此处输入图片说明

But this gives a syntax error:

INSERT INTO SomeTable
(SELECT 1 WHERE true) 
UNION
(SELECT 2 WHERE true) 

Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE true)' at line 4

What's the cause of the error?

How else would I insert multiple rows with a WHERE filter?

Remove parentheses and the where clause you have not a FROM clause so your where is not applicable

INSERT INTO SomeTable
SELECT 1 
UNION
SELECT 2 

or if you want a where condition you can use from dual

SELECT 1 from dual WHERE true
union 
SELECT 2 from  dual  WHERE true

Your parenthesis causes the problem. :

INSERT INTO SomeTable (col)
     SELECT 1 
     FROM . . 
     WHERE . . .
     UNION
     SELECT 2 
     FROM SomeTable 
     WHERE . . . ;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM