访问别名表

Accessing aliased tables

这道题错了。我对工会的运作方式有很大的误解。我现在正在阅读它。

编辑 04.12.2016 如果你仍然感兴趣,你可以去这里

我有这样的东西

with table3 as
(
  select t1.c1, t1.c2...
  from table1 t1
  union all
  select t2.c1, t2.c2...
  from table2 t2
)select * from table3

我需要将上面的所有行插入另一个 table

insert into table4 t4
(
  t4.c1, t4.c2...
)
select t3.c1, t3.c2...
from table3 t3 

我的问题是,这个插入是否有效。我在 table 1 和 2 中有名称相同的 clumns,我需要以不同方式引用它们吗?

需要这样写吗?

insert into table4 t4
    (
      t4.c1, t4.c2...
    )
    select t3.t1.c1, t3.t1.c2, t3.t2.c1...
    from table3 t3 

不需要别名

如果列匹配,您可以简单地使用插入 select

insert into table4 
( select t1.c1, t1.c2...
  from table1 t1
  union all
  select t2.c1, t2.c2...
  from table2 t2) 

否则你应该声明列名

insert insert into table4(c1, c2... )
( select t1.c1, t1.c2...
  from table1 t1
  union all
  select t2.c1, t2.c2...
  from table2 t2) 

withselect 语句的一部分。您可以 insert select 的结果,并且您可以在此 select 中使用 with。也许语法不是最直观的,但这应该有效:

insert into table4
with table3 as
(
  select t1.c1, t1.c2...
  from table1 t1
  union all
  select t2.c1, t2.c2...
  from table2 t2
) select * from table3;

不,你不需要(甚至不能)使用双别名。

假设您需要使用 UNION ALL,而不是将单个 insert-as-select 语句插入另一个 table,您可以尝试对来自不同的 tables:

with table1 as
(
  select t2.name     as t2_name,
         t2.address  as t2_address,
         t2.age      as t2_age,
         null        as t3_name,
         null        as t3_address,
         null        as t3_age,
  from table2 t2
  union all
  select null,
         null,
         null,
         t3.name,
         t3.address,
         t3.age
  from table3 t3
)