Postgresql 如何在查询中使用绑定数组参数

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

我对 postgresql 很陌生,正在努力使用数组

基本上我有一张像这样的桌子

bookIds 表

书号 位置_id 签出版本
12 1 10
15 1 12

从 Java 代码中,我将一组已签出的版本、位置 id 和书籍 id 传递给查询,并且查询需要

UPDATE bookIds SET checked_out_version = (values in the array?)
WHERE location_id = ANY (:locationIDS)
AND book_id = ANY (:bookIDS)

我很挣扎,因为我不断收到错误,postgresql 不支持使用更新语句的 set 子句更新带有数组的 col

我也尝试过循环,但显然它将签出的版本设置为数组中的最新版本

示例

如果我传递以下数组

bookIds [12,15]

位置IDS [1,1]

签出版本 [11, 20]

表格需要更新为如下所示

书号 位置_id 签出版本
12 1 11
15 1 20

有人可以帮忙吗?谢谢


This is the loop i tried 
    DO $$
    DECLARE
    i integer;
    BEGIN
    FOREACH i IN ARRAY :checkedOutVersions::integer[] LOOP
    RAISE NOTICE 'Value: %', i;
    UPDATE bookIds SET checked_out_version = i
    WHERE location_id = ANY (:locationIDs::bigint[])
    AND book_id = ANY (:bookIDs::integer[]);
    
    END LOOP;
    
    END $$;

postgresql spring-jdbc
1个回答
0
投票

您不需要 PL/pgSQL 块中的循环,因此也不需要

DO
命令。

使用简单的

UPDATE
语句并以
unnest()
作为设置返回函数,以锁步方式取消数组的嵌套:

UPDATE bookids
SET    checked_out_version = t.ver
FROM   unnest('{12,15}'::int[]   -- :bookIDs
            , '{1,1}'::bigint[]  -- :locationIDs
            , '{11,20}'::int[]   -- :checkedOutVersions
       ) AS t(book_id, loc_id, ver)
WHERE  location_id = t.loc_id
AND    book_id = t.book_id;
© www.soinside.com 2019 - 2024. All rights reserved.