Home >Database >Mysql Tutorial >How Can I Combine Arrays in PostgreSQL?
PostgreSQL provides various methods for manipulating arrays. One common operation is combining two arrays of equal length into pairs of elements. This article explores different approaches to achieving this task, considering PostgreSQL versions and specific use cases.
PostgreSQL 9.5 or later
PostgreSQL 9.5 introduces array_agg(array expression), allowing you to concatenate multiple arrays into one higher-dimensional array. This feature simplifies array combination tasks, eliminating the need for custom aggregate functions.
SELECT array_agg(ARRAY[a, b]) AS ab FROM unnest('{a,b,c}'::text[]) AS a, unnest('{d,e,f}'::text[]) AS b;
PostgreSQL 9.4
Prior to PostgreSQL 9.5, an alternative approach involves using unnest() with ROWS FROM.
SELECT ARRAY[a, b] AS ab FROM unnest('{a,b,c}'::text[], '{d,e,f}'::text[]) AS tmp(a, b);
For cases where you need to combine arrays into a multidimensional array, a custom aggregate function is necessary.
CREATE OR REPLACE FUNCTION array_agg_mult(anyarray) RETURNS SETOF anyarray LANGUAGE SQL AS $func$ SELECT ARRAY[ARRAY[a, b]] FROM unnest() AS unnest1(a, b); $func$;
SELECT array_agg_mult(ARRAY[ARRAY[a, b]]) AS ab FROM unnest('{a,b,c}'::text[]) AS a, unnest('{d,e,f}'::text[]) AS b;
The following function provides a generalized approach to zipping arrays of any type:
CREATE OR REPLACE FUNCTION zip(anyarray, anyarray) RETURNS SETOF anyarray LANGUAGE SQL AS $func$ SELECT array_agg_mult(ARRAY[ARRAY[a, b]]) FROM unnest() AS unnest1(a, b) JOIN unnest() AS unnest2(a, b) ON true; $func$;
The examples presented in this article showcase different scenarios for combining arrays:
PostgreSQL provides multiple options for combining arrays, depending on the version and desired output format. This article has comprehensively covered the available approaches, enabling you to select the most suitable method for your specific needs.
The above is the detailed content of How Can I Combine Arrays in PostgreSQL?. For more information, please follow other related articles on the PHP Chinese website!