gpt4 book ai didi

sql - 如何在 Postgresql 中选择和更新 JSON 数组元素?

转载 作者:行者123 更新时间:2023-11-29 11:26:36 30 4
gpt4 key购买 nike

我使用的是 9.6 版。我有这样的文档:

{
"name" : "John Doe",
"phones" : [
{
"type" : "mobile",
"number" : "555-555-0000",
"deleted": false
},
{
"type" : "home",
"number" : "555-555-0001",
"needsUpdated" : true
},
{
"type" : "work",
"number" : "555-555-0002"
}
]
}

我是这样创建的:

create table t_json (c_json json not null);

insert into t_json (c_json) values ('{"name":"John Doe","phones": [{"type":"mobile","number":"555-555-0000"},{"type":"home","number":"555-555-0001"},{"type": "work","number": "555-555-0002"}]}');

insert into t_json (c_json) values ('{"name":"Jane Dane","phones": [{"type":"mobile","number":"555-555-0030"},{"type":"home","number":"555-555-0020"},{"type": "work","number": "555-555-0010"}]}');

现在我想弄清楚如何A,选择名称为 John Doe 的行,并将他的手机号码更新为“555-555-0003 ".

从这里Postgresql 9.6 documentation我发现我可以像这样查询正确的文档:

select c_json from t_json where c_json->>'name' = 'John Doe';

但我没有看到如何按类型在电话数组中选择正确的子文档,并更新数字值。谁能帮帮我?

编辑

我需要假设子文档有额外的值并且不一致。所以我在上面添加了一些。我很确定此时如果不丢失数据就不可能进行此更新。

最佳答案

How to select the proper sub-document in the phones array by type?

如果你想得到电话号码,使用这个。对应文件为https://www.postgresql.org/docs/9.6/static/queries-table-expressions.html#QUERIES-LATERAL

SELECT c_json ->> 'name', phones.type, phones.number
FROM t_json
CROSS JOIN json_to_recordset(c_json -> 'phones')
AS phones("type" TEXT, "number" TEXT);

如果你想按电话号码搜索,这行得通:

SELECT * FROM t_json
WHERE (c_json -> 'phones')::JSONB @>
'[{"type":"mobile","number":"555-555-0000"}]'::JSONB;

How to update the number value?

如评论中所述,有一个类似的问题,How do I modify fields inside the new PostgreSQL JSON datatype?

还有其他方法可以做到这一点,比如

UPDATE t_json SET c_json = newvalue FROM (
SELECT to_json(updated) AS newvalue FROM (
SELECT c_json ->> 'name' as "name",
json_agg(json_build_object('type', phones.type, 'number',
CASE phones.type WHEN 'mobile' THEN '555-555-0003' ELSE phones.number END)
) AS phones
FROM t_json
CROSS JOIN json_to_recordset(c_json -> 'phones')
AS phones("type" TEXT, "number" TEXT)
WHERE c_json->>'name' = 'John Doe'
GROUP BY name
) as updated
) AS sub WHERE c_json ->> 'name' = 'John Doe';

关于sql - 如何在 Postgresql 中选择和更新 JSON 数组元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44297400/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com