我有以下数据:
name id url John 1 someurl Matt 2 cool Sam 3 stackoverflow我
如何写Postgres的SQL语句来选择这个数据到一个多维数组,即:
How can I write an SQL statement in Postgres to select this data into a multi-dimensional array, i.e.:
{{John, 1, someurl}, {Matt, 2, cool}, {Sam, 3, stackoverflow}}我见过这种前的Postgres阵列的使用,但不知道如何选择,从表中的数据到这个阵列格式。
I've seen this kind of array usage before in Postgres but have no idea how to select data from a table into this array format.
在这里假设所有列的类型为文本。
Assuming here that all the columns are of type text.
推荐答案您不能使用 ARRAY_AGG()来产生多维数组,至少达不到的PostgreSQL 9.4 。结果(但即将推出的的Postgres 9.5 艘船的新变种 ARRAY_AGG() 的就可以了!)
You cannot use array_agg() to produce multi-dimensional arrays, at least not up to PostgreSQL 9.4. (But the upcoming Postgres 9.5 ships a new variant of array_agg() that can!)
你得到了 @马特球的查询的是一组记录( the_table [ ] )。
What you get out of @Matt Ball's query is an array of records (the_table[]).
这是数组只能容纳相同的基本类型的元素。你明明有数字和字符串类型。转换所有列(即尚未)为文本来使其工作。
An array can only hold elements of the same base type. You obviously have number and string types. Convert all columns (that aren't already) to text to make it work.
您可以为此创建一个聚合函数就像我之前这里证明你。
You can create an aggregate function for this like I demonstrated to you here before.
CREATE AGGREGATE array_agg_mult (anyarray) ( SFUNC = array_cat ,STYPE = anyarray ,INITCOND = '{}' );电话:
SELECT array_agg_mult(ARRAY[ARRAY[name, id::text, url]]) AS tbl_mult_arr FROM tbl;请注意额外的 []数组层,使其成为一个多维数组(2-dimenstional,为precise)。
Note the additional ARRAY[] layer to make it a multidimensional array (2-dimenstional, to be precise).
即时演示:
WITH tbl(id, txt) AS ( VALUES (1::int, 'foo'::text) ,(2, 'bar') ,(3, '}b",') -- txt has meta-characters ) , x AS ( SELECT array_agg_mult(ARRAY[ARRAY[id::text,txt]]) AS t FROM tbl ) SELECT *, t[1][3] AS arr_element_1_1, t[3][4] AS arr_element_3_2 FROM x;更多推荐
选择数据到一个数组的Postgres
发布评论