使用Oracle中整个SQL语句的子查询可用性

时间:2013-12-15 11:39:03

标签: sql oracle

我正在尝试编写一个SQL语句,它在Oracle中多次重用With子句的子查询。

With mySubQ as (
    ...
) 

Select Something

From SomeTable, 
(
   Select *
   From mySubQ 
   where mySubQ.Something >= 0
) newSubQ

where mySubQ.Something = SomeTable.Something

这给了我错误 - ORA-32034不支持使用WITH子句

我错过了什么?

2 个答案:

答案 0 :(得分:5)

您需要加入mySubQ,而不仅仅是定义它。

WITH mySubQ AS (...)
SELECT Something
FROM SomeTable
JOIN mySubQ ON mySubQ.Something = SomeTable.Something
WHERE mySubQ.Something >= 0

如果将mySubQ的查询放在子查询中,则无法在主查询的mySubQ子句中引用WHERE。每个级别的查询只能访问自己的FROMJOIN子句中的表,而不能访问子查询中的表。

答案 1 :(得分:1)

以下是错误:where mySubQ.Something = SomeTable.Something

底部查询从SomeTable和子查询中选择别名newSubQ, 所以mySubQ.Something在这方面是未知的。

如果something是真正的列名,而不仅仅是“伪代码中的占位符”,那么此处还有另一个错误:Select Something - 列不明确,因为sometable和子查询有此列。

试试这个问题:

With mySubQ as (
    SELECT * FROM sometable
) 

Select newSubQ.Something

From SomeTable, 
(
   Select *
   From mySubQ 
   where mySubQ.Something >= 0
) newSubQ

where newSubQ.Something = SomeTable.Something
;

演示 - > http://www.sqlfiddle.com/#!4/88855/12

此演示还包含使用WITH子句的另一个示例:

WITH mySubQ AS (
  SELECT *
  FROM sometable
),

mySubQ_1 AS (
   SELECT *
   FROM mySubQ
   WHERE somethingelse = 1
),

mySubQ_2 AS (
   SELECT *
   FROM mySubQ
   WHERE something between 2 AND 5
)

SELECT *
FROM sometable s, mySubQ_1 m1, 
     (
        SELECT * FROM mySubQ_2
        WHERE something < 10
      ) m2
WHERE s.something = m1.something
  AND m1.somethingelse = m2.somethingelse