MySQL syntax for updating specific key/value pairs in JSON array
P粉386318086
P粉386318086 2023-11-06 14:50:43
0
1
771

I have a table in a MySQL 5.7.12 database with a JSON column.

The data in the column has the following structure (the json array may contain multiple json objects):

[{"ste": "I", "tpe": "PS"}, {"ste": "I", "tpe": "PB"}]

I want to write a UPDATE query to change the value of ste of tpe=PB.

This is my attempt:

Update user SET ext = JSON_SET(JSON_SEARCH(ext, 'one', 'PB', NULL, '$**.tpe'), '$.tpe', 'A');

The output of the query should be:

[{"ste": "I", "tpe": "PS"}, {"ste": "A", "tpe": "PB"}]

It doesn't work - it updates the column to:

"$[0].tpe"

How do I make it work?

edit

I think this makes more sense, but the syntax is still problematic

UPDATE user SET ext = JSON_SET(ext->JSON_SEARCH(ext, 'one', 'PS', NULL, '$**.tpe'), '$.tpe', 'A');


P粉386318086
P粉386318086

reply all(1)
P粉973899567

Hope you still need this.

Try using a variable path in your JSON_SET. Use JSON_SEARCH to get the variable path, then replace absolute pathtpe with ste to update its value. Works for me!

update user set ext= JSON_SET(ext, REPLACE(REPLACE(JSON_SEARCH(ext, 'one', 'PB'),'"',''),'tpe','ste'), 'A');
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!