PL SQL xmlelement:如何从同一张表的互斥条件中获取xml中的数据
Posted
技术标签:
【中文标题】PL SQL xmlelement:如何从同一张表的互斥条件中获取xml中的数据【英文标题】:PL SQL xmlelement: How to get data in xml from mutually exclusive condition on same tables 【发布时间】:2016-11-06 05:21:32 【问题描述】:我正在使用 XML 从数据库中获取一些数据。这是我的桌子:
设置表:
class code name
'm1' 1 Food1
'm1' 2 Food2
'p1' 1 PayInCash
'p2' 2 PayOnline
Customer Table:
customer_id food_name payment_method
CUS123 1 1
CUS123 2 2
如您所见,我使用了一些内部代码来映射其详细信息
我想编写将给出以下输出的查询:
Query Output:
customer_id food_name payment_method
CUS123 Food1 PayInCash
CUS123 Food2 PayOnline
我想检索 XML 格式的数据,这就是我使用 xmlelement 的原因。
SELECT xmlelement("customer_records",
XMLAGG(
xmlelement("record",
xmlelement("cus_id", customer_id),
xmlelement("food", food_name),
xmlelement("payment", payment_method)
)
)
)
FROM Customer
WHERE customer_id = 'CUS123';
您可以看到,由于条件,我无法加入。 请帮忙。
【问题讨论】:
【参考方案1】:尝试依赖子查询,方式如下:
SELECT customer_id,
( SELECT name FROM Settings s
WHERE class LIKE 'm%' AND s.code = c.food_name ) AS food_name,
( SELECT name FROM Settings s
WHERE class LIKE 'p%' AND s.code = c.payment_method ) AS payment_method
FROM customer c;
使用 XMLAGG 的示例:
SELECT xmlelement("customer_records",
XMLAGG(
xmlelement("record",
xmlelement("cus_id", customer_id),
xmlelement("food", food_name),
xmlelement("payment", payment_method)
)
)
)
FROM (
SELECT customer_id,
( SELECT name FROM Settings s
WHERE class LIKE 'm%' AND s.code = c.food_name ) AS food_name,
( SELECT name FROM Settings s
WHERE class LIKE 'p%' AND s.code = c.payment_method ) AS payment_method
FROM customer c
);
结果:
<customer_records>
<record>
<cus_id>CUS123</cus_id>
<food>Food1</food>
<payment>PayInCash</payment>
</record>
<record>
<cus_id>CUS123</cus_id>
<food>Food2</food>
<payment>PayOnline</payment>
</record>
</customer_records>
【讨论】:
以上是关于PL SQL xmlelement:如何从同一张表的互斥条件中获取xml中的数据的主要内容,如果未能解决你的问题,请参考以下文章
使用 pl/sql 中的 xmlelement 获取所有关系表数据
PL/SQL 函数中的 XmlRoot、XmlElement、InsertChildXml 给出 PLS-00201 必须声明标识符