How to compare two arrays and pick only the non matching elements In postgres

后端 未结 7 1953
一整个雨季
一整个雨季 2020-12-14 06:15

How can I pick only the non matching elements between two arrays.

Example:

base_array [12,3,5,7,8]
temp_array [3,7,8]

So here I wan

相关标签:
7条回答
  • 2020-12-14 07:05

    I would create a function using the same except logic as described by @a_horse_with_no_name:

    CREATE FUNCTION array_subtract(a1 int[], a2 int[]) RETURNS int[] AS $$
    DECLARE
        ret int[];
    BEGIN
        IF a1 is null OR a2 is null THEN
            return a1;
        END IF;
        SELECT array_agg(e) INTO ret
        FROM (
            SELECT unnest(a1)
            EXCEPT
            SELECT unnest(a2)
        ) AS dt(e);
        RETURN ret;
    END;
    $$ language plpgsql;
    

    Then you can use this function to change your base_array variable accordingly:

    base_array := array_subtract(base_array, temp_array);
    

    Using the @Denis's faster solution, and only SQL, we can express a generic function as

    CREATE FUNCTION array_subtract(anyarray,anyarray) RETURNS anyarray AS $f$
      SELECT array(
        SELECT unnest($1)
        EXCEPT
        SELECT unnest($2)
      )
    $f$ language SQL IMMUTABLE;
    
    0 讨论(0)
提交回复
热议问题