子查询中的Oracle无效标识符

时间:2013-10-16 07:42:19

标签: sql xml oracle oracle11g

我有这个问题:

SELECT
    XMLELEMENT("row", XMLATTRIBUTES(productMain.variant as "order"),
        (SELECT XMLELEMENT("attribute", XMLATTRIBUTES(product.id as "id") )
        FROM product where product.variant = productMain.variant
        )
    )

FROM
    (SELECT 
        DISTINCT product.variant 
    FROM 
        product
    WHERE
        product.fk_parent = 12345) productMain

我收到错误'无效标识符productMain.variant'

预期结果:

<row order="1">
    <attribute name="Example1"/>
    <attribute name="Example2"/>
    ...
</row>
<row order="2">
    ...
</row>

product

id | variant | name
_________________________
1  | 1       | Example1
2  | 1       | Example2
3  | 2       | Example3
4  | 3       | Example4
5  | 3       | Example5

...

SQLFIDDLE: http://www.sqlfiddle.com/#!4/e91a6/2

我发现,Oracle不会将嵌套的子查询关联到多个深度。

我如何仍然得到我想要的结果?

2 个答案:

答案 0 :(得分:0)

SELECT
XMLELEMENT("row", XMLATTRIBUTES(productMain.variant as "order"),
    (SELECT XMLELEMENT("attribute", XMLATTRIBUTES(product.id as "id") )
    FROM product,
    (SELECT DISTINCT variant FROM 
    product
    WHERE fk_parent = 12345) as productMain 
    where product.variant = productMain.variant
    )
)

FROM
(SELECT 
    DISTINCT variant 
FROM 
    product
WHERE
    fk_parent = 12345) productMain

答案 1 :(得分:0)

解决方案:

SELECT
XMLELEMENT("row", XMLATTRIBUTES(productMain.variant as "order"),

  (
  SELECT 
    XMLAGG(XMLELEMENT("attribute",XMLATTRIBUTES(product.name as "name"),product.variant)) FROM product 
    where product.fk_parent = 12345
    and product.variant = productmain.variant
  )

).getClobVal()

FROM
(SELECT 
    DISTINCT product.variant 
FROM 
    product
WHERE
    product.fk_parent = 12345) productMain;