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

PostgreSQL中通过数组参数批量删除多列匹配行

批量删除PostgreSQL表中多键匹配的行(基于数组参数)

需求

需要在PostgreSQL函数中通过数组参数,删除表中匹配以下(id1, id2)组合的行:

  • {id1: 4, id2: 8}
  • {id1: 4, id2: 9}
  • {id1: 5, id2: 8}

初始尝试与问题

尝试使用ANY配合数组的写法实现批量删除:

delete from mytable 
where (id1, id2) = ANY(Array [(4,8), (4,9), (5,8)])

该语句实际可正常执行,但在Supabase环境中报错:cannot compare dissimilar column types bigint and integer at record column 1,而表中id1、id2列均为bigint类型。

已知以下两种写法可行:

  1. 多字段匹配使用IN子句:
delete from mytable 
where (id1, id2) in ((4,8), (4,9), (5,8))
  1. 单字段批量匹配使用ANY数组:
delete from othertable 
where id = ANY(Array [1,2])

希望找到能结合两者特性(数组参数+多字段匹配)的实现方式,尝试多种组合未成功,也曾考虑临时表方案。

更新验证与最终解决方案

后续测试确认delete from mytable where (id1, id2) = ANY(Array [(1,3), (2,1)]);可正常执行,之前的Supabase报错是客户端导致的问题。

最终实现了接收两个数组参数的批量删除函数:

create or replace function bulk_delete (id1s bigint [], id2s bigint [])
  returns setof bigint
  language PLPGSQL
  as $$
begin
    return query WITH deleted AS (

      delete from mytable
      where (id1, id2) in (
        select id1, id2
        from unnest(id1s, id2s) as x(id1, id2)
      ) returning *

    ) SELECT count(*) FROM deleted;
end;
$$;

-- 函数调用示例
select bulk_delete(Array [1,1], Array [1,2]);

执行结果:

|bulk_delete|
|-----------|
| 2         |

补充说明

问题根源是语句中隐含的integer类型与Supabase默认的bigint(int8)类型冲突。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 15:35:43