【问题标题】:Required to create an empty table by joining multiple tables in Oracle DB需要通过连接 Oracle DB 中的多个表来创建空表
【发布时间】:2021-06-11 13:31:08
【问题描述】:

通过连接两个表创建空表时出错。

我有两个表 tab1 和 tab2,两个表中有很多共同的列名。

我试过了:

create table tab3 as
select * from tab1 a, tab2 b where a.id = b.id and 1=2;

这给出了 ORA-00957:列名重复。正如我上面提到的,这两个表之间有许多共同的列名。如果我通过一个一个地编写大约 500 个列名来准备创建表语句,那么它将消耗大量时间。请帮帮我。

【问题讨论】:

    标签: sql oracle


    【解决方案1】:

    简单的答案是,不要使用*。或者这就是重点,避免写五行列名?

    避免这些冲突的一种方法,但假设您要连接两个表中具有相同名称的所有列,而没有其他列,是执行类似

    create table new_table as
        select * 
        from   table_a natural join table_b
        where  null is not null
    ;
    

    (你可以猜到,顺便说一句,我更喜欢null is not null 而不是1 = 2;解析器似乎也更喜欢它,因为无论如何它都会将1 = 2 重写为null is not null。)

    您是否需要控制新表中列的顺序?如果这样做,无论您选择使用哪种连接语法,都需要将它们完全写在 select 子句中。

    【讨论】:

      【解决方案2】:

      这是一个有趣的问题。

      我必须提供的唯一想法是让另一个查询来组成您需要的查询

      select 'select ' || listagg(col_name, ', ') within group(order by 1) || 'from tab1 a,tab2 b where (a.id=b.id) and 1=2' 
        from (select 'a.' || column_name col_name from user_tab_cols where table_name = 'TAB1'
              union all 
              select 'b.' || column_name from user_tab_cols where table_name = 'TAB2')
      

      请注意子查询需要以大写形式指定表名

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-03-10
        • 2018-11-17
        • 1970-01-01
        • 2021-07-15
        • 1970-01-01
        相关资源
        最近更新 更多