如何更新存储在MySQL dB中的JSON数据数组中的数据值

bihw5rsg  于 12个月前  发布在  Mysql
关注(0)|答案(1)|浏览(222)

我把JSON数据放在一个dB的数组中。我想更新一个字段的值。
这将返回数组:

SELECT id, data 
from ComponentResult 
WHERE id = 2272;

返回数组的最后一个元素:

SELECT id, json_extract(data, '$[last]') 
from ComponentResult 
WHERE id = 2272;

这将返回包含我要更新的字段的对象:

SELECT json_extract(json_extract(data, '$[last]'), '$.AllResults') 
from ComponentResult 
WHERE id = 2272;`

这将返回我想要更新的值:

SELECT id, json_extract(json_extract(json_extract(data, '$[last]'), '$.AllResults'),'$.Accuracy') 
from ComponentResult 
WHERE id = 2272;

它目前设置为-99,我想将其更改为其他值,例如86。
我尝试了以下方法:

json_set(json_extract(json_extract(data, '$[last]'), '$.PrimaryResults') 
from ComponentResult 
WHERE id = 2272, '$.Accuracy',202);

update t set json_col = json_set(json_col, json_extract(json_extract(json_extract(data, '$[last]'), '$.AllResults'),'$.Accuracy'),'$.Accuracy',22) 
from ComponentResult 
WHERE id = 2272;`

理想情况下,最好是实际获取数组的最后一个元素,更改一个值,然后将更新后的元素作为新的“最后一个”值放回数组中。这允许以后审核当前值和先前值。
谢谢你

rqcrx0a6

rqcrx0a61#

这将返回数组[…]
返回数组的最后一个元素[…]
这将返回一个对象,其中包含我想要更新的字段[....]
作为启动器:你不需要嵌套调用json_extract来浏览JSON文档。相反,您可以使用MySQL JSON路径语法;这将为您提供要更改的属性的当前值:

select id, json_extract(data, '$[last].AllResults.Accuracy') 
from ComponentResult 
where id = 2272

如果你想在文档中将该值更改为86,你可以像这样使用json_set

update ComponentResult
set data = json_set(data, '$[last].AllResults.Accuracy', 86) 
where id = 2272

请注意,一般来说,将JSON数据存储在关系数据库中并不是一个好主意,特别是当您需要实际更新它时。

相关问题