引用嵌套查询中的列

时间:2017-12-21 07:17:20

标签: sql oracle

我使用的是Oracle 11g,使用嵌套SQL查询时出错。

当我尝试运行以下查询时,我得到了

  

" U.RSRC_ID":无效标识符*

这是SQL查询

SELECT u.first_name,
u.RSRC_ID,
(SELECT SUBSTR(SYS_CONNECT_BY_PATH (dn, ',') ,2) FROM
   (
      SELECT USER_NAME as dn, RSRC_ID as rsccid,
      ROW_NUMBER () OVER (ORDER BY user_name ) rn,
      COUNT (*) OVER () cnt
      FROM ADDRLOOKUP
      WHERE RSRC_ID  IN (u.RSRC_ID) AND primary_addr=4
   )
   WHERE rn        = cnt
   START WITH rn = 1
   CONNECT BY rn = PRIOR rn + 1 
) AS multipleDn

FROM USERINFO u
WHERE u.RSRC_ID      IN (123,124) ;

1 个答案:

答案 0 :(得分:2)

在Oracle中,您可以引用外层只有1级深度。在这种情况下,您将更深入地引用列2级。它在第9行:

WHERE RSRC_ID  IN (u.RSRC_ID)

编辑:您可以重写内部选择并将过滤器提升一级,这对性能不利,但结果应该没问题:

SELECT u.first_name,
u.RSRC_ID,
(SELECT SUBSTR(SYS_CONNECT_BY_PATH (dn, ',') ,2) FROM
   (
      SELECT USER_NAME as dn, RSRC_ID as rsccid,
      ROW_NUMBER () OVER (partition by RSRC_ID ORDER BY user_name) rn,
      COUNT (*) OVER (partition by RSRC_ID) cnt
      FROM ADDRLOOKUP
      WHERE primary_addr=4
   )
   WHERE rn        = cnt
     and rsccid = u.RSRC_ID
   START WITH rn = 1
   CONNECT BY rn = PRIOR rn + 1 
) AS multipleDn
FROM USERINFO u
WHERE u.RSRC_ID IN (123,124) ;