2016-12-02 40 views
0

这个问题是错误的。我对工会的工作原理有一些很大的误解。我现在正在阅读。访问别名表

编辑2016年4月12日 如果你还在位数的,你可以去这里 Selecting the right column

我有这样的事情

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

我需要插入另一个表从上面的所有行

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

我的问题是,这个插入工作。我将表1和表2中的列命名为相同,我是否需要以某种方式引用它们?

我需要这样写吗?

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

你已经拿到答案。 scaisEdge明确地回答说,使用'insert into t4(c1,c2)select t1.c1,t1.c2 ....)'完全没有问题,那么为什么你不把它标记为接受? –

+0

@Tho我写的问题不清楚,也不完整。他回答了他以为我问的一些问题。它没有帮助我。 –

+0

您问了一个问题并得到了正确的答案,所以您应该接受它。但是,如果您认为这个问题及其答案是没有用的,那么对您或任何未来的读者来说都不要删除它。 –

回答

0

没有别名需要

,如果你可以简单地插入使用的列匹配选择

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) 
+0

我需要别名,因为以后我可能需要使用table3执行一些其他操作。也许将其插入其他表中。 –

+0

您不需要用别名t4插入到table4中(插入到table4 t4(t4.col)中)。其余的你可以将你的选择与你喜欢的别名结合起来 – scaisEdge

1

withselect一部分声明。您可以insertselect的结果,您可以在此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; 

而且没有你不需要(甚至不可能)使用双别名。

0

假设你needto使用UNION ALL,而不是单个插入-AS-SELECT语句插入到另一个表,你可以尝试使用不同的别名,从不同的表中的列:

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 
)