我在PostgreSQL的my_table中的设置列中存储了一些XML。 XML类似于:
<Dictionary>
<ExportValues>
<ReplacementSet>
<type>TEST_CODE</type>
<ReplacementPair>
<Input>A1</Input>
<Output>One</Output>
</ReplacementPair>
<ReplacementPair>
<Input>A2</Input>
<Output>Two</Output>
</ReplacementPair>
<ReplacementPair>
<Input>A3</Input>
<Output>Three</Output>
</ReplacementPair>
</ReplacementSet>
<ReplacementSet>
<type>TEST_TYPE</type>
<ReplacementPair>
<Input>MTL</Input>
<Output>Metal</Output>
</ReplacementPair>
<ReplacementPair>
<Input>LQD</Input>
<Output>Liquid</Output>
</ReplacementPair>
<ReplacementPair>
<Input>SLD</Input>
<Output>Solid</Output>
</ReplacementPair>
</ReplacementSet>
</ExportValues>
</Dictionary>
我想获得以下输出:
type, Input, Output
TEST_CODE, A1, One
TEST_CODE, A2, Two
TEST_CODE, A3, Three
TEST_TYPE, MTL, Metal
TEST_TYPE, LQD, Liquid
TEST_TYPE, SLD, Solid
我能够使用以下SQL从类型节点获取值:
select xxx.*
from xmltable('/Dictionary/ExportValues/ReplacementSet'
passing xml((select settings
from my_table
limit 1))
columns replacement_value_type text path 'type') xxx
我可以使用以下SQL从Input和Output节点获取值:
select xxx.*
from xmltable('/Dictionary/ExportValues/ReplacementSet/ReplacementPair'
passing xml((select settings
from web_service
limit 1))
columns our_value text path 'OurValue',
their_value text path 'TheirValue') xxx
但是,我无法弄清楚如何使用ReplacementSet节点中的所有Input和Output节点值从相应类型节点中选择值。
我尝试过的所有内容都有错误,包括类型值,但输入和输出为空,或者输入和输出节点的类型和值为空。
这不是问题,但您必须明确地为“type”列指定XPath:
select x.*
from my_table,
xmltable('/Dictionary/ExportValues/ReplacementSet/ReplacementPair'
passing settings
columns
type text path '../type',
input text path 'Input',
output text path 'Output') x;
+-----------+-------+--------+
| type | input | output |
+-----------+-------+--------+
| TEST_CODE | A1 | One |
| TEST_CODE | A2 | Two |
| TEST_CODE | A3 | Three |
| TEST_TYPE | MTL | Metal |
| TEST_TYPE | LQD | Liquid |
| TEST_TYPE | SLD | Solid |
+-----------+-------+--------+
(6 rows)