ram*_*ams 13 arrays postgresql
我使用postgreSQL 9.1.在我的数据库中有一个看起来像的表
id | ... | values
-----------------------
1 | ... | {1,2,3}
2 | ... | {}
Run Code Online (Sandbox Code Playgroud)
其中id是一个整数,values是一个整数数组.数组可以为空.
我需要删除此列表.如果我查询
select id, ..., unnest(values)
from table
Run Code Online (Sandbox Code Playgroud)
我得到三行id = 1(正如预期的那样)并没有id = 2的行.有没有办法得到像这样的结果
id | ... | unnest
-------------------
1 | ... | 1
1 | ... | 2
1 | ... | 3
2 | ... | null
Run Code Online (Sandbox Code Playgroud)
即一个查询,其中还包含具有空数组的行?
a_h*_*ame 15
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;
Run Code Online (Sandbox Code Playgroud)
(请注意,我改名列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);
Run Code Online (Sandbox Code Playgroud)
在线示例:http://rextester.com/ALNX23313
使用左连接而不是交叉连接时,可以进一步简化:
select id, t.i
from the_table
left join lateral unnest(int_values) as t(i) on true;
Run Code Online (Sandbox Code Playgroud)
在线示例:http://rextester.com/VBO52351
这也适用于Postgres 10:
SELECT id, UNNEST(CASE WHEN "values" <> '{}' THEN "values" ELSE '{null}' END)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7921 次 |
| 最近记录: |