直接用-运算符是不行的, 网上用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] │
└─────────────────────────────────────────────────────────────────────────────────────────────┘