在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]                                                                                      │
└─────────────────────────────────────────────────────────────────────────────────────────────┘
相关推荐
怣5011 小时前
MySQL子查询零基础入门教程:从小白到上手(零基础入门版)
数据库·mysql
码界调试侠11 小时前
MongoDB 常用查询语法
数据库·mongodb
静听山水11 小时前
StarRocks导入数据【Stream Load】
数据库
藦卡机器人11 小时前
国产机械臂做的比较好的品牌有哪些?
大数据·数据库·人工智能
jiunian_cn11 小时前
【Redis】数据库管理操作
数据库·redis·缓存
l1t11 小时前
DeepSeek总结的DuckDB使用 WITH RECURSIVE 和 USING KEY 进行聚合的特性
sql·duckdb
_Johnny_12 小时前
ETCD 配额/空间告警模拟方案
网络·数据库·etcd
l1t12 小时前
DeepSeek总结的PostgreSQL解码GIF文件SQL移植到DuckDB的性能优化方法
sql·postgresql·性能优化
猫头虎12 小时前
基于信创openEuler系统安装部署OpenTeleDB开源数据库的实战教程
数据库·redis·sql·mysql·开源·nosql·database
爬山算法12 小时前
MongoDB(1)什么是MongoDB?
数据库·mongodb