Oracle:使用ON子句中的条件连接表

时间:2015-01-28 07:08:20

标签: oracle oracle11g oracle-sqldeveloper

我有两张表如下:

    Parent                          Child   
ABID    DEPARTMENT TIME         ABID    ABDEPARTMENT 
1       SC          10          1       MC           
1       -ALL-       15          2       SY           
1       MC          20                     
2       SC          20                             
2       -ALL-       15                             
2       MC          20                             

我想写一个连接查询,以便输出查询

  1. 应该具有匹配的ABID和部门。
  2. 如果父表中没有匹配的部门,则查询应该 使用DEPARTMENT'-ALL - '
  3. 返回行

    所以输出应该是

    ABID    DEPARTMENT TIME  ABID   ABDEPARTMENT
    1          MC        20   1       MC
    2        -ALL-       15   2       SY
    

    UPDATE1:

    我目前的查询是:

    select * from Child LEFT join Parent on Child.AbId = Parent.AbId and Child.ABDEPARTMENT= Parent.DEPARTMENT
    

    提供以下输出:

    ABID    DEPARTMENT ABID ABDEPARTMENT TIME     
    1          MC      1          MC      20
    2          SY      NULL      NULL     NULL 
    

1 个答案:

答案 0 :(得分:0)

可能的解决方案:

select *
  from parent p
  join child c on p.abid = c.abid and c.abdepartment = p.department
 union
select *
  from parent p
  join child c on p.abid = c.abid and p.department = '-ALL-'
 where not exists (select null
                     from parent p
                    where p.abid = c.abid
                      and c.abdepartment = p.department)