我有两张表格如下
表学生
PersonID firstName
1 John
2 Mike
表标记
mark_id person_id subject marks
1 1 English 50
2 1 Maths 75
以下查询给出xml如下
select XMLElement( "Students" ,
(select XMLAgg( XMLElement("Student" ,
XmlElement( "Student_id","id") ,
XmlElement( "First_Name","firstname")
))
FROM students )
)
AS "RESULT"
From dual
<Students>
<Student>
<Student_id>1</Student_id>
<First_Name>John</First_Name>
</Student>
<Student>
<Student_id>2</Student_id>
<First_Name>Mike</First_Name>
</Student>
<Students>
现在我需要使用students
左键加入表格Marks
并创建一个如下所示的xml
<Students>
<Student>
<Student_id>1</Student_id>
<First_Name>John</First_Name>
<Marks>
<subject>English</subject>
<mark>50</mark>
<subject>Maths</subject>
<mark>75</mark>
</Marks>
</Student>
<Student>
<Student_id>2</Student_id>
<First_Name>Mike</First_Name>
<Marks/>
</Student>
<Students>
如果我编写选择查询,我将如何实现它将为第一个学生返回两行,因为它有2行要加入第二个标记表。
答案 0 :(得分:1)
select XMLElement(
"Students" ,
XMLAgg(
XMLElement(
"Student" ,
XMLFOREST(
s."Student_id" AS "id",
s."First_Name" AS "firstname"
),
m.marks
)
)
)
FROM students s
LEFT OUTER JOIN
( SELECT person_id,
XMLELEMENT(
"Marks",
XMLAGG(
XMLFOREST(
"subject",
"marks" AS "mark"
)
)
) AS marks
FROM Marks
) m
ON ( s."PersonID" = m.person_id )
(注意:除非有特定的业务需求,否则为not good practice to use quoted identifiers for table/column names;只需在任何地方使用不带引号的标识符,并让oracle管理案例(in)敏感度。)