代码之家  ›  专栏  ›  技术社区  ›  Welton v3.62

如何在PostgreSQL中从XML查询同级节点

  •  0
  • Welton v3.62  · 技术社区  · 7 年前

    设置 中的列 在PostgreSQL中。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的节点:

    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
    

    但是,我不知道如何从相应的 包含所有 输入 输出 替换集

    类型 输入 输出 ,或为空 以及 输入 输出 节点。

    0 回复  |  直到 7 年前
        1
  •  2
  •   Pavel Stehule    7 年前

    这不是问题,但您必须为“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)