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
to int_values
as values
是保留字,不应用作列名)。
SQLFiddle:http://sqlfiddle.com/#!1/a0bb4/1 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 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 http://rextester.com/VBO52351