在PostgreSQL的数组替换NULL值 [英] Replace NULL values in an array in PostgreSQL

查看:1018
本文介绍了在PostgreSQL的数组替换NULL值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

SELECT ARRAY [1,2,3] - ARRAY [5,NULL,6]

SELECT ARRAY[1,2,3] - ARRAY[5,NULL,6]

我使用的contrib _int.sql包数组操作PostgreSQL中8.4
在上面的查询有一个 NULL 在右侧的数组。因为这个NULL值的,它抛出一个错误:

I am using contrib _int.sql package for array operations in postgresql 8.4 In the above query there is a NULL in right hand side array. Because of this NULL value, it throws an error:

"ERROR:  array must not contain nulls"

谁能帮我从数组中删除空值?

Can anyone help me to remove the null values from the array?

推荐答案

1)阵列的可以包含空值的PostgreSQL 8.4 +

1) Arrays can contain NULL values in PostgreSQL 8.4+

db=# SELECT ARRAY[5,NULL,6];
   array
------------
 {5,NULL,6}

2),但你的不能从另一个减去一个阵列中的标准的PostgreSQL 8.4。

2) But you cannot subtract one ARRAY from another in standard PostgreSQL 8.4.

db=# SELECT ARRAY[1,2,3] - ARRAY[5,NULL,6];
ERROR:  operator does not exist: integer[] - integer[]

3)您可以做,在8.4的PostgreSQL与的contrib包intarray 安装。

3) You can do that in PostgreSQL 8.4 with the contrib package intarray installed.

4),但你的不能减去包含NULL值的数组。

4) But you cannot subtract arrays containing NULL values.

5)您可以也减去阵列中的红宝石。请参见在这里的手工,或的在这里SO

5) You can also subtract arrays in Ruby. See here in the manual, or here on SO.

CREATE OR REPLACE FUNCTION f_int_array_replace_null (int[], int)
RETURNS int[] AS
$$
SELECT ARRAY (
    SELECT COALESCE(x, $2)
    FROM   unnest($1) x);
$$ LANGUAGE SQL IMMUTABLE;

<一个href=\"http://www.postgresql.org/docs/current/interactive/functions-array.html\"><$c$c>unnest()与PostgreSQL的介绍8.4 结果
对于旧版本,您可以使用<一个href=\"http://www.postgresql.org/docs/current/interactive/functions-srf.html\"><$c$c>generate_series():

CREATE OR REPLACE FUNCTION f_int_array_replace_null (int[], int)
RETURNS int[] AS
$$
SELECT ARRAY (
    SELECT COALESCE($1[i], $2)
    FROM   generate_series(1, array_upper($1, 1)) x(i));
$$ LANGUAGE SQL IMMUTABLE; 

电话:

event=# SELECT f_int_array_replace_null (ARRAY[5,NULL,6], 0);
 f_int_array_replace_null
--------------------------
 {5,0,6}

免责声明:这两个版本不适合多维数组

Disclaimer: both versions are not fit for multidimensional arrays.

这篇关于在PostgreSQL的数组替换NULL值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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