You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PostgreSQL如何按日期范围筛选XML字段中的issue_date?

问题场景

我有一个名为driver_license的XML字段,内容示例如下:

<driver_license>
 <no>123</no>
 <issue_date>2023-11-20</issue_date>
</driver_license>

需要筛选出issue_date大于指定日期的记录。在MSSQL中可通过以下查询实现:

SELECT * FROM persons AS t
WHERE t.driver_license.exist( 'driver_license/issue_date[.>=''2023-12-04'']' ) = 1

但在PostgreSQL中尝试的xmlexists语句无法生效:

WHERE xmlexists('//driver_license/issue_date[.>=''2023-12-04'']' PASSING BY REF t.driver_license )

问题原因是PostgreSQL的XPath引擎中,>=运算符默认仅支持整数等数值类型的直接比较,直接用字符串比较日期会不符合预期。

解决方案

方法1:XPath内转换为日期类型比较

利用XML Schema的xs:date()函数将节点值转为日期类型后再比较,需声明对应命名空间:

SELECT * 
FROM persons AS t
WHERE xmlexists(
    'declare namespace xs="http://www.w3.org/2001/XMLSchema";
     //driver_license/issue_date[xs:date(.) >= xs:date("2023-12-04")]'
    PASSING BY REF t.driver_license
);

方法2:提取日期到SQL层比较

先通过xpath()函数提取issue_date的文本值,转换为PostgreSQL的date类型后筛选,逻辑更直观:

SELECT * 
FROM persons AS t
WHERE (xpath('//driver_license/issue_date/text()', t.driver_license))[1]::date >= '2023-12-04'::date;

说明:xpath()返回节点值数组,[1]取第一个匹配值,::date完成类型转换后与指定日期比较。

内容的提问来源于stack exchange,提问作者Boris L

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 20:40:07