Remove array values in pgSQL

后端 未结 10 2229
不知归路
不知归路 2021-02-06 22:10

Is there a way to remove a value from an array in pgSQL? Or to be more precise, to pop the last value? Judging by this list the answer seems to be no. I can get the result I wan

10条回答
  •  一生所求
    2021-02-06 22:48

    My function for all types of arrays.

    Outer function:

    CREATE OR REPLACE FUNCTION "outer_array"(anyarray, anyarray) RETURNS anyarray AS $$
        SELECT
            "new"."item"
        FROM (
            SELECT
                ARRAY(
                    SELECT
                        "arr"."value"
                    FROM (
                        SELECT
                            generate_series(1, array_length($1, 1)) AS "i",
                            unnest($1)                              AS "value"
                    ) "arr"
                    WHERE
                        "arr"."value" <> ALL ($2)
                    ORDER BY
                        "arr"."i"
                ) AS "item"
        ) "new"
        $$
    LANGUAGE sql
    IMMUTABLE
    RETURNS NULL ON NULL INPUT
    ;
    

    Inner function:

    CREATE OR REPLACE FUNCTION "inner_array"(anyarray, anyarray) RETURNS anyarray AS $$
        SELECT
            "new"."item"
        FROM (
            SELECT
                ARRAY(
                    SELECT
                        "arr"."value"
                    FROM (
                        SELECT
                            generate_series(1, array_length($1, 1)) AS "i",
                            unnest($1)                              AS "value"
                    ) "arr"
                    WHERE
                        "arr"."value" = ANY ($2)
                    ORDER BY
                        "arr"."i"
                ) AS "item"
        ) "new"
    $$
    LANGUAGE sql
    IMMUTABLE
    RETURNS NULL ON NULL INPUT
    ;
    

提交回复
热议问题