【问题标题】:SQL Querying inside XML columnXML 列中的 SQL 查询
【发布时间】:2023-03-29 19:09:02
【问题描述】:

我正在尝试在具有 XML Column 的 SQL 表中进行查询。 表名:'购买' 列名:“XML_COL”

请在采购表下找到列名“XML_COL”的以下 xml 数据:

<ns1:Request xmlns:ns1="http://www.sample.com/hic/event/request"
xmlns:ns2="http://www.sample.com/hic/eventpayload/request">
<ns1:createeventRequest>
<ns1:eventPayLoad>
<ns2:eventPayLoad>
<Id>123456</Id>
</ns2:eventPayLoad>
</ns1:eventPayLoad>
</ns1:createeventRequest>
</ns1:Request>

我在下面写了查询:

`select * from  purchase,
XMLTABLE ('$d/Request/createeventRequest/eventPayLoad/eventPayLoad' PASSING  XML_COL  as  "d" 
COLUMNS 
Id  varchar(20)  PATH 'Id')  as a  where(a.Id like '1234%');`

但这给我返回了一个没有数据的空列。 但我的要求是它应该获取这个特定 ID 的所有数据。 如果有人遇到此类问题,请提供帮助。 我们是否需要在查询时也包含命名空间?还是我错过了什么?

【问题讨论】:

    标签: mysql sql xml database xmltable


    【解决方案1】:

    我觉得PATH 'Id'这个表达式有点简单...

    我不熟悉 MySQL 查询 XML 的能力...路径 Id 会尝试从当前节点(即第一个操作中的根节点)中查找元素“Id”。但是没有“Id”……你要么指定完整路径,从单个/开始在根节点开始,要么让引擎尝试深度搜索,从两个//开始

    这些路径应该可以工作:

    SELECT ExtractValue( 
    '<ns1:Request xmlns:ns1="http://www.sample.com/hic/event/request" xmlns:ns2="http://www.sample.com/hic/eventpayload/request">
      <ns1:createeventRequest>
        <ns1:eventPayLoad>
          <ns2:eventPayLoad>
            <Id>123456</Id>
          </ns2:eventPayLoad>
        </ns1:eventPayLoad>
      </ns1:createeventRequest>
    </ns1:Request>',
    
    '/ns1:Request[1]/ns1:createeventRequest[1]/ns1:eventPayLoad[1]/ns2:eventPayLoad[1]/Id[1]' ) AS result;
    

    如果只有一个元素具有值(在您的情况下为“Id”),您可以像这样使用简单的深度搜索:

    SELECT ExtractValue( 
    '<ns1:Request xmlns:ns1="http://www.sample.com/hic/event/request" xmlns:ns2="http://www.sample.com/hic/eventpayload/request">
      <ns1:createeventRequest>
        <ns1:eventPayLoad>
          <ns2:eventPayLoad>
            <Id>123456</Id>
          </ns2:eventPayLoad>
        </ns1:eventPayLoad>
      </ns1:createeventRequest>
    </ns1:Request>',
    
    '//Id[1]' ) AS result;
    

    但是 - 一般来说 - 建议尽可能具体...

    【讨论】:

    • 感谢您的回复。我也尝试在路径下的查询中提供路径 /ns1:Request[1]/ns1:createeventRequest[1]/ns1:eventPayLoad[1‌​]/ns2:eventPayLoad[1‌​]/Id ,但它没用。
    【解决方案2】:

    刚刚破解了查询...当在 XML 中使用名称空间而不是整个路径时,我发现最好使用“/*//”,它通过 XML 遍历所需的元素标记。

    最终查询:

    select * from purchase, XMLTABLE('$d' PASSING XML_COL as "d" COLUMNS Id varchar(20) PATH '/*//Id') as a where(a.Id like '1234%') with ur

    使用'with ur'有助于读取数据库中尚未提交的数据。

    如果有帮助,请发布 cmets。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-18
      • 2012-10-18
      • 2017-07-01
      • 2018-07-06
      • 2010-09-08
      • 2012-10-23
      • 1970-01-01
      相关资源
      最近更新 更多