Oracle:同步兩張表的相同字段


有一個需求需要同步兩張表的相同字段,比如表A和表B,這兩張表是不同的用戶下的表,表結構是一樣的。

一開始我簡單寫了一個sql語句,如下:

update ord_log1 A
    set 
        (A.pid, A.beg_ticket_no, A.end_ticket_no) = 
        (select B.pid, B.beg_ticket_no, B.end_ticket_no
            from 
                newhl.ord_log B
            where
                A.mer_id = B.mer_id 
            and 
                A.ord_id = B.ord_id)
    where
             A.acct_date between '20190507' and '20190508');
commit;

運行一下,報錯,ORA-01407:無法更新字段pid為NULL,想了一下,估計是表B中pid有NULL的值,而A表pid確實不能為NULL,於是加上條件B.pid is not null。運行一下,還是報同樣的錯,那就有點奇怪了。查看一下表B所有的pid的值,沒有為NULL的啊,那是怎么回事。

找了很久,原來是外層的where條件符合的數據范圍(X條記錄)多余內層where的條件(Y條記錄),這些超過的記錄都會自動設置為NULL,所以一直報無法更新字段pid為NULL的錯誤。(參考http://blog.itpub.net/28602568/viewspace-2076239/)於是新的sql語句修改如下:

update ord_log1 A
    set 
        (A.pid, A.beg_ticket_no, A.end_ticket_no) = 
        (select B.pid, B.beg_ticket_no, B.end_ticket_no
            from 
                newhl.ord_log B
            where
                A.mer_id = B.mer_id 
            and 
                A.ord_id = B.ord_id
            and 
                A.acct_date between '20190424' and '20190512')
    where
        exists
            (select B.pid, B.beg_ticket_no, B.end_ticket_no
                from 
                    newhl.ord_log B
                where
                    A.mer_id = B.mer_id 
                and 
                    A.ord_id = B.ord_id
                and 
                    A.acct_date between '20190424' and '20190512');

        

運行,可以了。還是平時寫sql語句比較少,沒有什么經驗啊。


免責聲明!

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



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