1. 程式人生 > >sql 查詢兩張表結構差異、兩張結構相同表的資料差異

sql 查詢兩張表結構差異、兩張結構相同表的資料差異

*1.比較表結構 *:

(select column_name,table_name
from user_tab_columns
where table_name = ‘EMP’
minus
select column_name,table_name
from user_tab_columns
where table_name = ‘DEPT’)
union
(select column_name,table_name
from user_tab_columns
where table_name = ‘DEPT’
minus
select column_name,table_name
from user_tab_columns
where table_name = ‘EMP’);
注意:表結構資訊儲存在user_tab_columns,規定表的名稱全部為大寫形式


在這裡插入圖片描述
結果:得到了兩張表不同結構的列名,以及表名

2.比較表資料:

(select *
from EMP
minus
select *from EMP2)
union
(select *
from EMP2
minus
select * from EMP)
注意:前提是表結構一樣,可以進行資料差異查詢
得到下列結果:
在這裡插入圖片描述
結果:得到了兩張結構相同表的差異資料

但是無法區分哪一行的資料,屬於那張表,因此加上子查詢,利用虛擬列名稱,進行區分·,sql如下所示:
select a.*,‘EMP’ from (select *
from EMP
minus
select * FROM EMP2) a

union
select b.*,‘EMP2’ from
(select *
from EMP2
minus
select * FROM EMP) b

得到的查詢結果,如下所示:
在這裡插入圖片描述
結果:增加了EMP行,加以區分;