给定两个数组如何获取不在两个数组中的项目?

Given two arrays how to get items that are not in both?

我在 postgresql 中有两个数组:

CREATE OR REPLACE FUNCTION func()
  RETURNS void AS
$BODY$ 
declare 
        first integer[];
        second integer[];
        array_vb integer[];
        array_vb2 integer[];  
begin

    code.... 

    select array_agg(id) into first
    from a
    where id = any (array_vb);

    select array_agg(id) into second
    from a
    where id = any (array_vb2);

end;
 $BODY$
  LANGUAGE plpgsql VOLATILE

我想添加一个 raise notice 来打印第一个但不是第二个的所有项目

例如:

first = [1,10,15,3,7]

second = [1,3,15,4]

它将打印 10,7

我该怎么做?

您可以使用 intarray extension:

create extension if not exists intarray;

select array[1,10,15,3,7] - array[1,3,15,4] as result;

 result 
--------
 {7,10}
(1 row)
create or replace function f(a1 int[], a2 int[])
returns void as $body$ 
begin

    raise notice '%', (
        select string_agg(i::text, ',')
        from
            unnest (a1) a1(i)
            left join
            unnest (a2) a2(i) using (i)
        where a2.i is null
    );

end;
$body$ language plpgsql volatile
;
select f(array [1,10,15,3,7], array [1,3,15,4]);
NOTICE:  10,7
 f 
---

(1 row)

注意上面的函数,照原样可以标记为immutable

您可以创建一个 returns 所需数组结果的函数:

create or replace function array_except(a1 int[], a2 int[])
  returns int[]
as
$$
    select array_agg(i)
    from ( 
      select i
      from unnest(a1) i
      except 
      select a2
      from unnest(a2) a2
    ) t;
$$ 
language sql;

函数returns一个包含第一个数组中但不在第二个数组中的元素的数组。

你可以在你的实际函数中使用上面的函数:

create or replace function foo()
  returns void
as
$BODY$
declare 
  _first integer[];
  _second integer[];
begin

    _first := array[1,10,15,3,7];
    _second := array[1,3,15,4];
    raise notice 'Result %', array_except(_first, _second);

end;
$BODY$
LANGUAGE plpgsql;

您可以使用 PostgreSQL unsent 函数:

SELECT ARRAY(SELECT unnest(first) EXCEPT SELECT unnest(second))

示例:

SELECT ARRAY(SELECT unnest(ARRAY[1,10,15,3,7]) EXCEPT SELECT unnest(array[1,3,15,4]))

给出:

array
--------
{10,7}

参见 SQLFiddle here