如何将数组传递给节点的 pg 客户端以供 unnest() 函数使用?

问题描述 投票:0回答:1

我希望能够更改列表的顺序位置。每个列表都有自己的位置字段。当我更新列表顺序时,我想将其保存到数据库中。因此,我以正确的顺序传递一个包含列表 id 字段的数组,并使用中等复杂的查询来更新列表:

with pos as (
    select 
        id as pos_id,
        row_number() over() as position
    from (
        select unnest(
            array[36, 33, 35, 37, 46, 39, 40, 41, 43, 45, 38, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 58, 59, 60, 61, 62, 65, 66, 67, 68, 78, 79, 82, 83]
        ) as id 
    ) a 
)  
update lists l
    set position = pos.position
from 
    pos
where 
    l.id = pos.pos_id

这在 pg_admin 中工作得很好,但是当我尝试将其放入 Node 中时,它就不起作用了。

我尝试使用这些形式发送 $1 参数:

  1. 解除嵌套($1)
  2. unnest($1::bigint[])
  3. 取消嵌套($1:列表)
  4. 取消嵌套(数组[$1])
  5. unnest(数组[$1::bigint[])
  6. unnest(数组[$1::列表)
  7. unnest(数组[$1::bigint[])
  8. unnest(ARRAY[' + Positions.join(', ') + '])
  9. unnest('{' + Positions.join(', ') + '}')
  10. unnest('{' + Positions.join(', ') + '}'::bigint[])

没有一个起作用。其中一些返回解析错误,一些返回“需要添加显式类型转换”错误。在这种情况下,如何将数组传递给 pool.query ?

javascript node.js postgresql node-pg-pool
1个回答
0
投票

当我尝试时,我应该犯一些错误。因为选项2, unnest($1::bigint) 工作得很好,因为我试图一一确认所有表格。

所以正确的代码是:

let positions = [36, 33, 35, 37, 46, 39, 40, 41, 43, 45, 38, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 58, 59, 60, 61, 62, 65, 66, 67, 68, 78, 79, 82, 83];

pool.query('with pos as ( select id as pos_id, row_number() over() as position from ( select unnest($1::bigint[]) as id ) a )  update listas l set position = pos.position from pos where l.id = pos.pos_id',
    [positions], (error) => {
... whatever
© www.soinside.com 2019 - 2024. All rights reserved.