如果oracle中没有子记录或子记录,如何获取父记录

时间:2015-07-22 22:28:13

标签: sql oracle join

我有一个场景,如果子记录不存在,我需要通过仅显示父记录和子记录为NULL来检索父记录。结构如下所示。

SELECT A.ROW_ID AS PARENT_ROW_ID,
           B.ROW_ID AS CHILD_ROW_ID,
          C.ROW_ID AS GRANDCH_ROW_ID
  FROM MANAGER A,
       EMPLOYEE B,
       CONTRACTOR C
 WHERE A.ROW_ID(+) = B.PAR_ROW_ID
   AND B.ROW_ID = C.PAR_ROW_ID
   AND A.ROW_ID IN ('1-HC3')

所以,当我执行这一切时,它返回零记录而不是给我父记录。当然,另一方面,还有其他记录有儿童记录,而且他们正确地来了。请建议我在这种情况下做什么

1 个答案:

答案 0 :(得分:2)

更改查询以使用ANSI连接使连接条件更加清晰:

SELECT A.ROW_ID AS PARENT_ROW_ID,
       B.ROW_ID AS CHILD_ROW_ID,
       C.ROW_ID AS GRANDCH_ROW_ID
FROM   MANAGER A
       LEFT OUTER JOIN
       EMPLOYEE B ON ( A.ROW_ID = B.PAR_ROW_ID )
       LEFT OUTER JOIN
       CONTRACTOR C ON ( B.ROW_ID = C.PAR_ROW_ID )
WHERE  A.ROW_ID = '1-HC3'

编辑 - 回答您的评论

只需检查该类型是否是您想要的类型之一,或者是NULL

SELECT A.ROW_ID AS PARENT_ROW_ID,
       B.ROW_ID AS CHILD_ROW_ID,
       C.ROW_ID AS GRANDCH_ROW_ID
FROM   MANAGER A
       LEFT OUTER JOIN
       EMPLOYEE B ON ( A.ROW_ID = B.PAR_ROW_ID )
       LEFT OUTER JOIN
       CONTRACTOR C ON ( B.ROW_ID = C.PAR_ROW_ID )
WHERE  A.ROW_ID = '1-HC3'
AND    (   B.TYPE IN ( 'SALES', 'MARKET', 'HR' )
       OR  B.TYPE IS NULL )