选择数据到一个数组的Postgres [英] Selecting data into a Postgres array

查看:211
本文介绍了选择数据到一个数组的Postgres的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下数据:

name          id             url

John          1              someurl.com
Matt          2              cool.com
Sam           3              stackoverflow.com

如何写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.com}, {Matt, 2, cool.com}, {Sam, 3, stackoverflow.com}}

我见过这种前的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 艘船<一个href=\"http://www.postgresql.org/docs/devel/static/functions-aggregate.html#FUNCTIONS-AGGREGATE-TABLE\"相对=nofollow>的新变种 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆