我们有一个“order_json”列来存储和表示引用该行的所有项目的顺序。
客户端可以在 json 数组中的特定索引中添加项目。
但是,我觉得我的解决方案相当笨拙且效率低下。
SELECT JSON_AGG(element)
FROM
(WITH first_part AS (
SELECT id, jsonb_array_elements(order_json) AS element
FROM my_boards
WHERE id = 5
LIMIT 2 -- means that client wants to add the element at index 2
)
, second_part AS (
SELECT id, jsonb_array_elements(order_json) AS element
FROM my_boards
WHERE id = 5
OFFSET 2
)
SELECT element
FROM first_part
UNION ALL
-- the new json element the client wants to add at index 2
SELECT element
FROM (values(5,'{"item_id": 999}'::JSONB)) n(id, element)
UNION ALL -- regular 'union' can mess up the order
SELECT element
FROM second_part) nj;
有没有更有效的方法在特定索引处插入 json 对象?
jsonb_insert()
可以将元素插入到数组的任意位置:
以下:
with data (order_json) as (
values ('[{"item_id": 1}, {"item_id": 2}, {"item_id": 3}, {"item_id": 4}]'::jsonb)
)
select jsonb_insert(order_json, '{1}', '{"item_id": 999}')
from data
将返回
[{"item_id": 1}, {"item_id": 999}, {"item_id": 2}, {"item_id": 3}, {"item_id": 4}]
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句