Oracle SQL - 使用IF NOT EXISTS的最佳方法吗?

时间:2016-09-23 15:08:42

标签: null case exists

我非常感谢您提供以下帮助:

SELECT A.EMPLOYEE, A.PHONE AS CELL, B.PHONE AS OFFICE, C.PHONE AS HOME
FROM PHONE_NUMBERS A, PHONE_NUMBERS B, PHONE_NUMBERS C
WHERE A.EMP_NUM = B.EMP_NUM
  AND A.EMP_NUM = C.EMP_NUM
  AND A.PHONE_TYPE = 'CELL'
  AND B.PHONE_TYPE = 'OFFICE'
  AND C.PHONE_TYPE = 'HOME'

我的问题如下:如果员工拥有CELL和HOME手机类型,但OFFICE手机类型不存在任何条目,则查询将不会返回,因为OFFICE不存在。我尝试了CASE语句,但没有手机类型,CASE没有什么可比的。我已阅读很多关于IF NOT EXISTS的帖子,但我不确定这是否是正确的方法。我希望查询返回所有EMP_NUM,如果特定的PHONE_TYPE不存在,则返回null。

2 个答案:

答案 0 :(得分:0)

使用“Full Outer”加入

SELECT coalesce(h.EMPLOYEE, o.EMPLOYEE, c.EMPLOYEE) Employee,
       c.PHONE AS CELL, o.PHONE AS OFFICE, h.PHONE AS HOME
FROM PHONE_NUMBERS h
   full join PHONE_NUMBERS o
      On o.EMP_NUM = h.EMP_NUM 
         and h.PHONE_TYPE = 'HOME'
         and o.PHONE_TYPE = 'OFFICE'
   full join PHONE_NUMBERS C
      On c.EMP_NUM = h.EMP_NUM 
         and c.PHONE_TYPE = 'CELL'

答案 1 :(得分:0)

我想你可以试试OUTER JOIN。 这是带有(+)

的OUTER JOIN的示例
None