在postgres和duckdb中比较两个数组并只挑选不匹配的元素

直接用-运算符是不行的, 网上用AI生成的文档很不负责地误导大家。

复制代码
select array[1,2]-array[1];
错误:  操作符不存在: integer[] - integer[]
第1行select array[1,2]-array[1];
                      ^
提示:  没有匹配指定名称和参数类型的操作符. 您也许需要增加明确的类型转换.

duckdb 也会报错

复制代码
select [1,2] -[1];
Binder Error:
No function matches the given name and argument types '-(INTEGER[], INTEGER[])'. You might need to add explicit type casts.

文档中有array_remove函数,但一次只能删除一个元素

复制代码
postgres=# select array_remove(ARRAY[1,2,3,2], 2);
 array_remove
--------------
 {1,3}

还是人类的回答靠谱, 将数组转成表的行,再用array()函数转回来。

复制代码
postgres=# select unnest(array[1,2,3]) except select unnest(array[1,2]);
 unnest
--------
      3
(1 行记录)

postgres=# select array(select unnest(array[1,2,3]) except select unnest(array[1,2]));
 array
-------
 {3}
(1 行记录)

此法在duckdb也可以用

复制代码
select array(select unnest(array[1,2,3]) except select unnest(array[1,2]));
┌──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
│ (SELECT CASE  WHEN ((array_agg(COLUMNS(*)) IS NULL)) THEN (list_value()) ELSE array_agg(COLUMNS(*)) END FROM ((SEL...  │
│                                                       int32[]                                                        │
├──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┤
│ [3]                                                                                                                  │
└──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘

除了上面的方法,duckdb还可以用list_filter配合contains函数。

复制代码
select list_filter([3, 4, 5], lambda x : not contains([2,4],x  ));
┌─────────────────────────────────────────────────────────────────────────────────────────────┐
│ list_filter(main.list_value(3, 4, 5), (lambda x: (NOT contains(main.list_value(2, 4), x)))) │
│                                           int32[]                                           │
├─────────────────────────────────────────────────────────────────────────────────────────────┤
│ [3, 5]                                                                                      │
└─────────────────────────────────────────────────────────────────────────────────────────────┘
相关推荐
jiayou6421 小时前
KingbaseES 实战:深度解析数据库对象访问权限管理
数据库
李广坤2 天前
MySQL 大表字段变更实践(改名 + 改类型 + 改长度)
数据库
爱可生开源社区3 天前
2026 年,优秀的 DBA 需要具备哪些素质?
数据库·人工智能·dba
随逸1773 天前
《从零搭建NestJS项目》
数据库·typescript
加号34 天前
windows系统下mysql多源数据库同步部署
数据库·windows·mysql
シ風箏4 天前
MySQL【部署 04】Docker部署 MySQL8.0.32 版本(网盘镜像及启动命令分享)
数据库·mysql·docker
李慕婉学姐4 天前
Springboot智慧社区系统设计与开发6n99s526(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
数据库·spring boot·后端
百锦再4 天前
Django实现接口token检测的实现方案
数据库·python·django·sqlite·flask·fastapi·pip
tryCbest4 天前
数据库SQL学习
数据库·sql
jnrjian4 天前
ORA-01017 查找机器名 用户名 以及library cache lock 参数含义
数据库·oracle