从数组中删除一个非唯一值 [英] Remove one, non-unique value from an array
问题描述
给出PostgreSQL 9.6中的该表:
Given this table in PostgreSQL 9.6:
CREATE TABLE test_table (
id int PRIMARY KEY
, test_array text[]
);
行如下:
INSERT INTO test_table (id, test_array)
VALUES (1 , '{A,A,A,B,B,B}');
如何删除单个 B值?
我不能使用:
UPDATE test_table
SET test_array = array_remove(test_array, 'B')
WHERE id = 1;
,因为它删除了值 B的所有所有元素。我只是想删除一个元素(例如第一个元素)。
as it removes all elements of value 'B'. I am just looking to remove a single element (say, the first one).
有什么想法吗?
推荐答案
基于您在dba.SE上找到的并有效利用的旧答案:
Based on my old answer on dba.SE that you found and put to good use:
- Delete array element by index
您可能会更进一步:
CREATE OR REPLACE FUNCTION f_array_remove_elem1(anyarray, anyelement)
RETURNS anyarray LANGUAGE sql IMMUTABLE AS
'SELECT $1[:idx-1] || $1[idx+1:] FROM array_position($1, $2) idx';
此函数将要删除的元素值作为第二个参数。相应地使用多态伪类型 anyelement
使其适用于任何数组类型。
This function takes the value of the element to remove as 2nd parameter. Using the polymorphic pseudo-type anyelement
accordingly to make this work for any array type.
然后 UPDATE
就是:
UPDATE test_table
SET test_array = f_array_remove_elem1(test_array, 'B')
WHERE id = 1;
db<>小提琴此处
使用我的原始函数 f_array_remove_elem()
取索引位置而不是元素值,您可以不使用子查询:
While using my original function f_array_remove_elem()
that takes the index position instead of the element value, you could do without a subquery:
UPDATE test_table
SET test_array = f_array_remove_elem(test_array, array_position(test_array, 'B'))
WHERE id = 1;
可能甚至比我的新功能快。
我的旧答案底部的较简单版本适用于Postgres 9.6。
Might even be a bit faster than my new function.
And note that the simpler version at the bottom of my old answer works for Postgres 9.6.
这篇关于从数组中删除一个非唯一值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!