在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]                                                                                      │
└─────────────────────────────────────────────────────────────────────────────────────────────┘
相关推荐
审判长烧鸡18 小时前
PostgreSQL之索引/函数/触发器
数据库·postgresql·触发器·函数·索引
Data_Journal18 小时前
如何使用cURL更改User Agent
大数据·服务器·前端·javascript·数据库
Python私教19 小时前
GenericAgent PySide6 桌面应用深度解析:悬浮按钮 + 聊天面板的原生 Qt 方案
开发语言·数据库·qt
byoass19 小时前
企业云盘与设计软件深度集成:AutoCAD/Revit/SolidWorks插件开发与API集成实战
服务器·网络·数据库·安全·oracle·云计算
爬山算法20 小时前
MongoDB(113)如何使用第三方工具进行MongoDB监控?
数据库·mongodb
早日退休!!!21 小时前
大模型推理瓶颈七层分析模型
java·服务器·数据库
大山同学21 小时前
claudecode精炼版-CoreCoder
数据库·人工智能·claude code·corecoder
of Watermelon League21 小时前
5、使用 pgAdmin4 图形化创建和管理 PostgreSQL 数据库
数据库·postgresql
Dontla1 天前
Python asyncpg库介绍(基于Python asyncio的PostgreSQL数据库驱动)连接池、SQLAlchemy
数据库·python·postgresql
俺不要写代码1 天前
数据库:DQL
数据库·sql·mysql