我使用postgreSQL 9.1.在我的数据库中有一个表

id | ... | values
-----------------------
1  | ... | {1,2,3}
2  | ... | {}

其中id是一个整数,values是一个整数array.数组可以是空的.

我需要取消这个列表.如果我质疑

select id, ..., unnest(values)
from table

对于id=1,我得到了三行(正如预期的那样),对于id=2,我没有得到任何行.有没有办法得到这样的结果

id  | ... | unnest
-------------------
1   | ... | 1
1   | ... | 2
1   | ... | 3
2   | ... | null

i、 e.也包含空数组行的查询?

推荐答案

select id, 
       case 
         when int_values is null or array_length(int_values,1) is null then null
         else unnest(int_values)
       end as value
from the_table;

(请注意,我将列values重命名为int_values,因为values是保留字,不应用作列名).

SQLFiddle:http://sqlfiddle.com/#!1/a0bb4/1


Postgres 10不允许再像那样使用unnest().

您需要使用横向连接:

select id, t.i
from the_table
   cross join lateral unnest(coalesce(nullif(int_values,'{}'),array[null::int])) as t(i);

在线示例:http://rextester.com/ALNX23313


当使用左连接而不是交叉连接时,可以进一步简化:

select id, t.i
from the_table
 left join lateral unnest(int_values) as t(i) on true;

在线示例:http://rextester.com/VBO52351

Postgresql相关问答推荐

如何在postquist中修剪第一/后文件名

Postgres SQL执行加入

如何在PostgreSQL中对深度嵌套的jsonb属性创建索引

是否可以在psql查询输出中删除新行末尾的+号?

如何将 jackc/pgx 与连接池、上下文、准备好的语句等一起使用

在Postgres中如何连接具有相同名称列的表并更改列名称?

使用psql的copy语句时如何压缩数据?

转到 time.Time to postgresql timestamptz 无法用 time.Now() 保存

如何使用有限的varchar在postgres中存储单词é

在 to_tsquery 中转义特殊字符

Postgres/psycopg2 - 插入字符串数组

如何从元组列表中 Select 与多列匹配的行?

PostgreSQL 如何比 SQLite 更快地执行写入?

SELECT INTO 具有多个归因

如何在 PostgreSQL 中创建 guid

manage.py 迁移时必须是关系 django_site 的所有者

Rails:PG :: InsufficientPrivilege:错误:permission denied for relation schema_migrations

null 计算结果为 false 的情况

有没有办法确保 WHERE 子句在 DISTINCT 之后发生?

基于秒的 Postgresql 日期差异