选择数据到一个数组的Postgres

编程入门 行业动态 更新时间:2024-10-14 10:39:32
本文介绍了选择数据到一个数组的Postgres的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有以下数据:

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

本文发布于:2023-10-27 10:34:51,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1533113.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   数据   Postgres

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!