我想比较两个数组,忽略元素和重复的顺序。
我可以在两个方向进行收容检查,但有更好/更快的解决方案吗?
select * from my_table where my_table.a1 @> my_table.a2 and
my_table.a2 @> my_table.a1
答案 0 :(得分:1)
从我的internal testing开始,似乎这两个变体速度最快(甚至比@>
+ <@
检查更快),并且它们都可以处理NULL
个太:
where (select array_agg(distinct e order by e) from unnest(arr1) e)
= (select array_agg(distinct e order by e) from unnest(arr2) e)
where array(select distinct e from unnest(arr1) e order by e)
= array(select distinct e from unnest(arr2) e order by e)
后者通常要快一点,但有时候不会。这可能取决于很多事情,f.ex。数组的基数等等。
答案 1 :(得分:0)
使用不必要且不同的示例:
t=# create or replace function so62(a1 anyarray,a2 anyarray) returns boolean as
$$
declare
_r boolean := false;
_a text;
begin
with p as (select distinct unnest(a1) order by 1) select array_agg(unnest) into _a from p;
with p as (select distinct unnest(a2) order by 1) select array_agg(unnest)::text = _a into _r from p;
return _r;
end;
$$ language plpgsql;
CREATE FUNCTION
(@poz后更新的功能请注意,需要两个except
进行比较)
<强>试验:强>
t=# with c as (
select '{1,null,2,2}'::int[] a1,'{2,1,null}'::int[] a2
)
select a1 @> a2, a2 @> a1,so62(a1,a2)
from c;
?column? | ?column? | so62
----------+----------+------
f | f | t
(1 row)
在此示例中, @>
和<@
根本不起作用。
另请阅读Compare arrays for equality, ignoring order of elements