在SQL精细打印的格式选择阵列 [英] Selecting arrays in nicely printed format in SQL

查看:123
本文介绍了在SQL精细打印的格式选择阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想选择一个整数的二维数组,并指挥输出到文件中。有没有办法,我可以写一个PostgreSQL声明,这将使格式化很好的select语句的输出的任何方式。因为这是二维数组的元素整数每个数组中的是自己的路线。

I'm trying to select for a two dimensional array of integers, and directing the output to a file. Is there any way that I can write a postgresql statement that would make the output of the select statement nicely formatted. As in each array of integers that is an element of the 2D array is on its own line.

现在,我只是得到这样的输出:

Right now I just get this output:

SELECT array FROM table LIMIT 1;
{{0,0,0},{1,1,1},{2,2,2},{3,3,3},{0,0,0},{1,1,1},{2,2,2},{3,3,3}
,{0,0,0},{1,1,1},{2,2,2},{3,3,3},{0,0,0},{1,1,1},{2,2,2},{3,3,3}
,{0,0,0},{1,1,1},{2,2,2},{3,3,3},{0,0,0},{1,1,1},{2,2,2},{3,3,3}}

和我想更多的像这样得到的东西:

And I would like to get something more like this:

{0,0,0}
{1,1,1}
{2,2,2}
...

我可以与一些解析查询返回后做,但如果可能的Postgres自身做到这一点,将是理想的。

I can do this after the query returns with some parsing, but if its possible to do it in Postgres itself that would be ideal.

推荐答案

有几种方法。一种方法是强制转换数组文本,然后用 regexp_split_to_table分裂它() 。结果
此功能在 PostgreSQL 8.3版本present或更高版本

There are several ways. One way is to cast the array to text and split it up with regexp_split_to_table().
This function is present in PostgreSQL 8.3 or later.

SELECT regexp_split_to_table(trim(my_2d_intarr::text, '{}'), '},{');

输出:

0,0,0
1,1,1
2,2,2

如果你想封闭括号(也许你不?),将它们添加回是这样的:

If you want the enclosing brackets (maybe you don't?), add them back like this:

SELECT '{' || regexp_split_to_table(trim(my_2d_intarr::text, '{}'), '},{') || '}';

Ourtput:

Ourtput:

{0,0,0}
{1,1,1}
{2,2,2}

替代

这也应该一起工作的的PostgreSQL 8.2 或甚至更早,但我没有测试。

Alternative:

This should also work with PostgreSQL 8.2 or maybe even earlier, but I did not test that.

SELECT my_2d_int_arr_var[x:x][1:3]
  FROM (SELECT generate_series(1, array_upper(my_2d_intarr, 1), 1)::int4 AS x)) x

输出:

{{0,0,0}}
{{1,1,1}}
{{2,2,2}}

<子>(您可能要剥离一些大括号..)

否则,我会写,通过数组循环一个PLPGSQL功能。相当容易的。

Else, I would write a plpgsql function that loops through the array. Fairly easy.

也有相关的 UNNEST() 功能,但它返回每个基本元素(整数在这种情况下)的行,所以它在这里没有用。

There is also the related unnest() function, but it returns a row per base element (integer in this case), so it's no use here.

一(!快)的方式来输出结果: 复制

One (fast!) way to output the result: COPY.

这篇关于在SQL精细打印的格式选择阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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