PostgreSQL:仅当元素是唯一的时才将元素附加到jsonb数组

时间:2017-11-15 10:13:07

标签: sql json postgresql jsonb

我创建了一个PostgreSQL(v10.0),如下所示。

CREATE TABLE test (id INT, animals jsonb)

INSERT INTO test VALUES
   (1, '["[monkeys, 10]", "[hamsters, 7]", "[foxes, 3]"]'),
   (2, '["[monkeys, 10]", "[hamsters, 7]", "[foxes, 3]"]')

然后我按如下方式追加新动物:

UPDATE test
SET animals = animals || '["[hamsters, 7]", "[chicken, 2]"]'::jsonb
WHERE id = 1;

但是,我想追加几个元素,但只包含那些尚未包含在数组中的元素。

在这种情况下,那只是[鸡,2]

1 个答案:

答案 0 :(得分:1)

最简单的可能是:

t=# with c as (select distinct e,min(o) over (partition by e) o from test, jsonb_array_elements(animals || '["[hamsters, 7]", "[chicken, 2]"]'::jsonb) with ordinality t(e,o) where id =1)
, r as (select jsonb_agg(e order by o) z from c)
t-# update test set animals = z from r where id = 1;
UPDATE 1
t=# select * from test;
 id |                             animals
----+------------------------------------------------------------------
  2 | ["[monkeys, 10]", "[hamsters, 7]", "[foxes, 3]"]
  1 | ["[monkeys, 10]", "[hamsters, 7]", "[foxes, 3]", "[chicken, 2]"]
(2 rows)