简体   繁体   English

Oracle select 语句显示两个表中的匹配列? 没有数据,只有两个表中都存在的列名

[英]Oracle select statement to show matching columns in two tables ? No data just the column names that exist in both the tables

How can i show all the columns which are similar in two tables in oracle db?如何在 oracle db 的两个表中显示所有相似的列?

It sounds like you just want something like this.听起来你只是想要这样的东西。

select t1.column_name 
  from all_tab_columns t1
 where t1.owner = <<table1 owner>>
   and t1.table_name = <<table1 name>>
intersect
select t2.column_name 
  from all_tab_columns t2
 where t2.owner = <<table1 owner>>
   and t2.table_name = <<table1 name>>

You could write it as a join or as an exists as well if you'd rather.如果您愿意,您也可以将其写为joinexists But intersect makes more sense to me from a readability perspective.但从可读性的角度来看, intersect对我来说更有意义。 You could use dba_tab_columns or user_tab_columns rather than all_tab_columns depending on what privileges you have in the database, whether you know the tables are in your current schema, etc.您可以使用dba_tab_columnsuser_tab_columns而不是all_tab_columns ,具体取决于您在数据库中拥有的权限、您是否知道表在当前架构中等。

Another approach is aggregation:另一种方法是聚合:

select atc.column_name,
       (case when count(*) = 2 then 'Both'
             when min((atc.owner) = :owner1 and min(atc.table_name) = :table1
             then 'Table1 only'
             else 'Table2 only'
        end) 
from all_tab_columns atc
where (atc.owner = :owner1 and atc.table_name = :table1) or
      (atc.owner = :owner2 and atc.table_name = :table2) 
group by atc.column_name;

The advantage to this approach is that it easily generalizes to showing all columns:这种方法的优点是它很容易推广到显示所有列:

select atc.column_name 
from all_tab_columns atc
where (atc.owner = :owner1 and atc.table_name = :table1) or
      (atc.owner = :owner2 and atc.table_name = :table2) 
group by atc.column_name
having count(*) = 2;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM