为什么 Common table 表达式不适用于 INSERT SELECT

Why Common table expression does not work with INSERT SELECT

我正在尝试在我的 INSERT 中使用常见的 table 表达式。 当我这样做时:

with A as (select col1,col2 from table1) select * from A

有效 但是当我这样做时:

with A as (select col1,col2 from table1) 
insert into table2 (col1,col2) (select col1,col2 from A)

我得到:

found "INSERT" (at char XXXXX) expecting `SELECT' or `'(''

您的查询应该适用于大多数数据库。但是,Oracle 和早期版本的 Postgres 将 CTE 放在 select 旁边。因此,如果您使用的是 Oracle、早期版本的 Postgres 或 Postgres 派生的数据库:

insert into table2 (col1, col2)
    with A as (select col1, col2 from table1) 
    select col1, col2 from A;

另外,select 查询不需要括号。它不是子查询。