【问题标题】:INSERT SELECT WHERE insert multiple rows from constantsINSERT SELECT WHERE 从常量中插入多行
【发布时间】:2017-08-28 09:26:31
【问题描述】:

我正在尝试插入多行,这些行的值不是取自现有表,而是从外部提供,以及使用 INSERT ... SELECT ... WHERE 的 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)

我想查询不插入任何行,因为where 条件为假。但是,where 子句仅适用于最后一个select,第 2 个selects 不受where 子句的影响。

如何改正?

【问题讨论】:

  • 您可以尝试使用 select * from (all your query ) where 1 >2

标签: mysql select sql-insert insert-select


【解决方案1】:

只需将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 ;

【讨论】:

  • @PankajSinghal 你知道你需要接受这个问题,这样社区才能知道找到了解决方案吗?
  • @MasivuyeCokile 是的,我知道。但是,你知道我不能接受一个答案,除非它是 10 分钟吗?
  • @PankajSinghal 不知道,抱歉。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多