在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]                                                                                      │
└─────────────────────────────────────────────────────────────────────────────────────────────┘
相关推荐
这个DBA有点耶5 天前
MVCC深入:Read View、版本链与快照读——InnoDB并发控制的内核
数据库·mysql·架构
DBA_G5 天前
从地面到云霄:GBase数据库在民航三大场景的落地实践
数据库
自由能燃气设备5 天前
商用全预混低氮冷凝锅炉免费方案vs付费方案对比+选型避坑指南
大数据·数据库·人工智能
科创致远5 天前
科创致远 ESOP 系统核心效能与实战价值展示
大数据·数据库·人工智能·精益工程
漂着的圆木5 天前
Agent 功能参与度:Copilot 怎么算
sql·数据分析·agent·githubcopilot·度量
geovindu5 天前
sql: Transaction & Concurrency Patterns using postgresql 18
postgresql·数据库开发·数据库架构
2601_962218615 天前
万象生鲜系统称重自动多退少补算法解决生鲜非标品痛点
大数据·数据库·人工智能·python·算法
张洛闻Eren5 天前
k8s云原生【第十课】:水平 Pod 自动扩缩容
运维·数据库·云原生·kubernetes·github
于平安5 天前
MySQL-触发器
数据库·mysql
白远山5 天前
上海24小时自助健身房解决方案实战指南与经验分享
java·数据库·架构·需求分析