[oracle/Sql]怎樣比較兩表的差異?


比如有這么一個表:

create table test02(
   id number(8,0) primary key,
   name nvarchar2(20),
   sal number(5,0)
)

可以這樣給它充值:

insert into test02 
select rownum,dbms_random.string('*',dbms_random.value(6,20)),dbms_random.value(1000,30000)  from dual
connect by level<=200
order by dbms_random.random

然后以此建立一張新表:

create table test03 as select * from test02;

現在 test02,test03內容都是一致的。

 

但在漫長的生活中,風化和侵襲會導致兩者有所不同,下面用更新語句來模擬兩者產生的變化:

update test02 set name='bill' where id=1;
update test02 set name='andy' where id=2;

update test03 set sal=22222 where id=22;
update test03 set sal=33333 where id=33;
update test03 set sal=44444 where id=44;

這樣,兩表就產生了五條數據的不同,那么怎么通過sql語句知道不同點呢?可以執行下面SQL:

select t2.*,t3.* from test02 t2 full join test03 t3 on (t2.name=t3.name and t2.sal=t3.sal) where (t2.id IS NULL or t3.id IS NULL) order by t2.id,t3.id

執行效果:

SQL> select t2.*,t3.* from test02 t2 full join test03 t3 on (t2.name=t3.name and t2.sal=t3.sal)
  2  where (t2.id IS NULL or t3.id IS NULL) order by t2.id,t3.id;

        ID NAME                                            SAL         ID NAME                                    SAL
---------- ---------------------------------------- ---------- ---------- ---------------------------------------- ----------
         1 bill                                          11595
         2 andy                                          23646
        22 CTCUCDUAOFEDWDOSZJ                            24070
        33 SRMKTDAHKCSKMU                                 5758
        44 ZCFLYSMOSHYWNX                                22652
                                                                        1 ZUNZKJEEDGTHC                         11595
                                                                        2 SGRNZOIFBMITAMKSYTQE                  23646
                                                                       22 CTCUCDUAOFEDWDOSZJ                    22222
                                                                       33 SRMKTDAHKCSKMU                        33333
                                                                       44 ZCFLYSMOSHYWNX                        44444

已選擇10行。

 

如果是兩表沒有差別呢?讓我們以test02為基礎創建一個test04來模擬:

create table test04 as select * from test02;

再比較一下:

SQL> select t2.*,t4.* from test02 t2 full join test04 t4 on (t2.name=t4.name and t2.sal=t4.sal)
  2  where (t2.id IS NULL or t4.id IS NULL) order by t2.id,t4.id;

未選定行

這便是兩表完全一致的情況。

以上的方法也適用於View和查詢結果的比較。

--2020年1月29日--

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM