在Oracle中检查所有子记录是否存在父ID

时间:2014-12-01 08:41:07

标签: sql-server oracle

表A:

PRID  PRTRNSID
1     1
1     2
1     3
2     1
2     2

在此表中,对于PRID 1,有3个子记录,对于PRID 2,有2个子记录

表B:

EVENTTRNID PRID PRTRNSID
 1            1    1
 2            1    2
 3            2    1
 4            2    2

在此表中,prid 2的所有子记录都存在,而prid 1,3rd number子记录丢失,所以我需要以下列方式输出

OutPut:

PRID  Status
1     Pending
2     Done

任何人都可以帮我检查所有儿童ID是否存在于另一张桌子中?

1 个答案:

答案 0 :(得分:1)

试试这个

with A as (select 1 PRID, 1 PRTRNSID from dual
          union all
          select 1, 2 from dual
          union all
          select 1, 3 from dual
          union all
          select 2, 1 from dual
          union all
          select 2, 2 from dual),
     B as (select 1 EVENTTRNID, 1 PRID, 1 PRTRNSID from dual
          union all
          select 2, 1, 2 from dual
          union all
          select 3, 2, 1 from dual
          union all
          select 4, 2, 2 from dual)

select A.prid, case when min(case when B.EVENTTRNID is null then 0 else B.EVENTTRNID end) = 0 then 'Pending' else 'Done' end Status
  from A left join B on B.PRID = A.PRID and B.PRTRNSID = A.PRTRNSID
 group by A.prid