开发者

Merging two arrays in PostgreSQL as index and value?

开发者 https://www.devze.com 2023-03-17 03:38 出处:网络
Assuming I have two array fields in a table, like this: Column |Type| --------+-----------+ index| integer[] |

Assuming I have two array fields in a table, like this:

 Column |   Type    |
--------+-----------+
 index  | integer[] | 
 value  | integer[] | 

Where both index and value are equal in length, and the values in 'index' are guaranteed to be unique, for example:

SELECT * FROM ArrayTest;
   index   | value             
-----------+-----------------------------------
 {1,3,5,6} | {100, 103, 105, 106}

How would I make a query which returns a new array, where the values in 'index' are used as array indexes, and the values in 'value' become the values associated with the given index, i.e. something like:

SELECT some_array_function(index, value) as newarray;
            new_array
开发者_JAVA技巧--------------------------------
{100, NULL, 103, NULL, 105, 106}

What I want to achieve is the same as array_combine in PHP.


While overall a bad idea to store data like this, one way to do it is to use the unnest function and the process the results on the client side:

SELECT unnest(index), unnest(value) FROM ArrayTest;

 unnest | unnest 
--------+--------
      1 |    100
      3 |    103
      5 |    105
      6 |    106

If you must have a function to create a new array here's a short function that will do it:

CREATE FUNCTION array_stitch(index_array integer[], value_array integer[]) RETURNS integer[]
    LANGUAGE plpgsql IMMUTABLE
    AS $$
DECLARE
    ptr INTEGER;
    new_array INTEGER[];
BEGIN
    FOR ptr IN 1..array_upper(index_array,1) LOOP
            new_array[index_array[ptr]] := value_array[ptr];
    END LOOP;

    RETURN new_array;
END;
$$;

EDIT: Here's another way to do it:

SELECT array_agg(val order by idx) as output_array
FROM (SELECT generate_series(1,idx[array_upper(idx,1)]) from array_test) as g(idx)
LEFT JOIN (SELECT unnest(idx) as idx, unnest(val) as val FROM array_test\
    ) as data_points USING (idx);


Try this simple procedure:

CREATE OR REPLACE FUNCTION merge_arrays(index INTEGER[], value INTEGER[]) RETURNS INTEGER[] AS $$
DECLARE
    arr_size INTEGER;
    max_index INTEGER;
    result INTEGER[];
    i INTEGER;
    index_pos INTEGER := 1;
BEGIN
    arr_size := array_upper(index, 1);
    max_index := index[arr_size];

    FOR i IN 1..max_index LOOP
        IF index @> ARRAY[i] THEN
            result := result || value[index_pos];
            index_pos := index_pos + 1;
        ELSE
            result := result || '{NULL}'::INTEGER[];
        END IF;

    END LOOP;

    RETURN result;
END;
$$ LANGUAGE PLPGSQL;

Usage:

SELECT merge_arrays(index ,value) from array_test;
0

精彩评论

暂无评论...
验证码 换一张
取 消