码迷,mamicode.com
首页 > 其他好文 > 详细

3.7 检测两个表中是否有相同的数据

时间:2017-04-24 15:47:32      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:esc   解决方案   view   comm   查找   rom   coalesce   war   union all   

问题:要知道两个表或视图中是否有相同的数据(基数和值)。考虑这个视图:

create view V
as
    select * from emp where deptno !=10
        union all
    select * from emp where ename = ‘WARD‘   

现要检测这个视图与表emp中的数据是否完全相同。员工“WARD”行重复,说明解决方案不仅要显示不同行,还要显示重复行。

解决方案:
1.首先,查找出表emp中存在而试图v中没有的行
2.然后合并(union all)在视图V中存在,而在表emp中没有的行。

select * from
    (
        select e.empno,e.ename,e.job,e.mgr,e.hiredate,
            e.sal,e.comm,e.deptno,count(*)  as cnt
        from emp e
        group by empno,ename,job,mgr,hiredate,sal,comm,deptno
    ) e
where not exists
    (
    select null from
        (
            select v.empno,v.ename,v.job,v.mgr,v.hiredate,v.sal,v.comm,v.deptno
                count (*) as cnt
            from v
            group by empno,ename,job,mgr,hiredate,sal,comm,deptno
        )v
        where v.empno = e.empno
            and v.ename = e.ename
            and v.job = e.job
            and v.mgr = e.mgr
            and v.hiredate = e.hiredate
            and v.sal = e.sal
            and v.deptno = e.deptno
            and v.cnt = e.cnt
            and coalesce(v.comm.0) = coalesce(e.comm,0)
    )
    union all

    select * from
    (
        select e.empno ,e.ename,e.ename,e.job,e.mgr,e.hiredate,e.sal ,e.comm,e.deptno,count(*) as cnt
        from v
        group by empno,ename,job,mgr,hiredate,sal,comm,deptno
    )v
    where not exists (
        select null from (
            select e.empno,e.ename,e.job,e.mgr,e.hiredate,e.sal,e.comm,e.deptno,count(*) as cnt
            from emp e
            group by empno,ename,job,mgr,hiredate,sal,comm,deptno
            )e
        where v.empno = e.empno
            and v.ename = e.ename
            and v.job = e.job
            and v.mgr = e.mgr
            and v.hiredate = e.hiredate
            and v.sal = e.sal
            and v.deptno = e.deptno
            and v.cnt = e.cnt
            and coalesce(v.comm.0) = coalesce(e.comm,0)

    );
    
    


   

3.7 检测两个表中是否有相同的数据

标签:esc   解决方案   view   comm   查找   rom   coalesce   war   union all   

原文地址:http://www.cnblogs.com/liang545621/p/6756878.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!