致梦想

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语句比较少,没有什么经验啊。

posted on 2019-05-10 14:49  致梦想  阅读(3435)  评论(0编辑  收藏  举报

导航