问题描述
如何在oracle db中显示两个表中相似的所有列?
解决方法
听起来你只是想要这样的东西。
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>>
如果您愿意,也可以将其写为 join
或 exists
。但从可读性的角度来看,intersect
对我来说更有意义。您可以使用 dba_tab_columns
或 user_tab_columns
而不是 all_tab_columns
,具体取决于您在数据库中拥有的权限、您是否知道这些表在您当前的架构中等。
另一种方法是聚合:
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;
这种方法的优点是它很容易推广到显示所有列:
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;