比较2个表以检查差异

时间:2016-09-21 07:49:04

标签: sql database oracle oracle11g

我有2个表,我必须比较才知道是什么数据。我试图找到查询,但还无法找到。要比较的数据存储在detail1和detail2中,定义如下:

detail1
D1_ID (integer)
D1_MASTERID (integer)

带数据

| D1_MASTERID | D1_ID | 
|      1      |   1   | 
|      1      |   3   | 



detail2
D2_ID (integer)
D2_MASTERID (integer)

带数据

| D2_MASTERID | D2_ID | 
|      1      |   1   | 
|      1      |   2   | 
|      1      |   4   | 

master
MASTER_ID (integer)

带数据

| MASTERID |
|     1    |

我尝试了很多方法,这是最后一次尝试仍然没有效果:

select MASTER_ID, D1_ID, D2_ID
FROM master
LEFT JOIN detail1 ON MASTERID=D1_MASTERID
LEFT JOIN detail2 ON MASTERID=D2_MASTERID

我得到的结果就像是

| MASTERID | D1_ID | D2_ID |
|    1     |   1   |   1   |
|    1     |   1   |   2   |
|    1     |   1   |   4   |
|    1     |   3   |   1   |
|    1     |   3   |   2   |
|    1     |   3   |   4   |

我想得到的是:

| MASTERID | D1_ID | D2_ID |
|    1     |   1   |   1   |
|    1     |       |   2   |
|    1     |   3   |       |
|    1     |       |   4   |

我在考虑左联盟可以这么做......但是它没有用。 还是子标题?我真的不确定

我查看了该页http://sql.sh/cours/jointures,但它也没有帮助......

THX

2 个答案:

答案 0 :(得分:4)

在Oracle中,您可以使用var array = [{ DisplayGroup: 'ABC', Value: 5 }, { DisplayGroup: 'DEF', Value: 3 }, { DisplayGroup: 'ABC', Value: 6 }, { DisplayGroup: 'GHI', Value: 2 }]; Array.prototype.groupBy = function( key,value){ var newArray = [] var temp = [] this.filter((c,i,a)=> { var ob = {} if(temp.indexOf(c[key]) == -1){ ob[c[key]] = c[value] ; newArray.push(ob) temp.push(c[key]); } else{ newArray.filter((e)=> { if(e[c[key]]){ e[c[key]] = e[c[key]] + c[value] } }); } }) return newArray; } console.log(array.groupBy('DisplayGroup','Value'))

FULL OUTER JOIN

或者master是否包含id,两个详细表中都不存在:

select NVL(d1_masterid, d2_masterid) as masterid,  d1_id, d2_id
from   
        detail1
FULL OUTER JOIN
        detail2
on      d1_masterid = d2_masterid
and      d2_id =  d1_id
;

答案 1 :(得分:2)

您可以先详细查询detail1和detail2中的匹配行。然后添加detail1中没有匹配的detail2行列表:

select  master_id, d1_id, d2_id
from    master
left join
        detail1
on      master_id = d1_master_id
left join
        detail2
on      master_id = d2_master_id
        and d1_id = d2_id
union all
select  master_id, d1_id, d2_id
from    master
left join
        detail2
on      master_id = d2_master_id
left join
        detail1
on      master_id = d1_master_id
        and d1_id = d2_id
where   d1_id is null -- Row not found in d1

Example at SQL Fiddle.