INSERT SELECT WHERE从常量中插入多行

时间:2017-04-03 13:25:46

标签: mysql select sql-insert insert-select

我正在尝试插入多个行,这些行的值不是从现有表中获取的,而是使用IFS从外部提供的where条件。

以下查询无效:

INSERT ... SELECT ... WHERE

我想查询不插入任何行,因为mysql> insert into `my_table` SELECT 1 as a, 2 as b, 3 as c from dual UNION ALL SELECT 4 , 5 , 6 from dual UNION ALL SELECT 7 , 8 , 9 from dual where 1>2 ; Query OK, 2 rows affected (0.01 sec) Records: 2 Duplicates: 0 Warnings: 0 mysql> select * from my_table; +---+---+------+ | a | b | c | +---+---+------+ | 1 | 2 | 3 | | 4 | 5 | 6 | +---+---+------+ 2 rows in set (0.00 sec) 条件为false。但是,where子句仅适用于最后where,而前2 select不受select子句的影响。

我该如何纠正?

1 个答案:

答案 0 :(得分:3)

UNION ALL子查询包装在子查询中,以便将WHERE应用于整个结果集:

insert into `my_table` 
select a, b, c 
from (
   SELECT 1 as a, 2 as b, 3 as c 
   from dual 

   UNION ALL 

   SELECT 4 , 5 , 6 
   from dual 

   UNION ALL 

   SELECT 7 , 8 , 9  
   from dual ) as t
where a > b ;