Postgresql - 在选择中使用 xpath 时如何将 xml 数据类型更改为整数

use*_*796 1 xml postgresql xpath

我尝试从一个 xml 字段中选择值并将选定的值插入到另一个整数类型的表字段中。

询问:

INSERT INTO "Match" 
select 
unnest(xpath('./game/id/text()', "File"))
FROM "Files"
Run Code Online (Sandbox Code Playgroud)

Select 工作正常,但是当我尝试插入时,会发生错误:

SQL error:
ERROR:  column "id" is of type integer but expression is of type xml
LINE 3: unnest(xpath('./game/id/text()', "File")),

HINT:  You will need to rewrite or cast the expression.
Run Code Online (Sandbox Code Playgroud)

当我尝试使用强制转换更改 xml 类型时,出现另一个错误:

SQL error:
ERROR:  cannot cast type xml to integer
LINE 3: cast(unnest(xpath('./game/id/text()', "File"))as integer)
Run Code Online (Sandbox Code Playgroud)

当我尝试使用 XMLSERIALIZE 更改类型时,会发生另一个错误:

SQL error:
ERROR:  argument of XMLSERIALIZE must not return a set
LINE 3: XMLSERIALIZE(CONTENT unnest(xpath('./game/id/text()', "File"...
Run Code Online (Sandbox Code Playgroud)

如何将选定的值插入另一个表?

And*_*mar 6

首先选择 XML“id”节点中的文本:

xpath('game/id/text()', col1)
Run Code Online (Sandbox Code Playgroud)

这将返回一个您取消嵌套的数组,从而导致零行或多行之间:

unnest(xpath('game/id/text()', col1))
Run Code Online (Sandbox Code Playgroud)

Across join lateral允许您为unnest(xpath(...))表中的每一行运行:

cross join lateral
        unnest(xpath('game/id/text()', col1)) xp(id)
Run Code Online (Sandbox Code Playgroud)

最后,Postgres 不能将 XML 转换为数字。您需要对文本进行中间转换:

select  id::text::int
from    YourTable
cross join lateral
        unnest(xpath('game/id/text()', col1)) xp(id)
Run Code Online (Sandbox Code Playgroud)

SQL Fiddle 中的示例。