How to update json data in a column using mysql?

by elise_daugherty , in category: MySQL , 3 months ago

How to update json data in a column using mysql?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by lily , 3 months ago

@elise_daugherty 

To update JSON data in a column using MySQL, you can use the JSON_SET() function. Here's an example of how to do it:


Let's say you have a table named my_table with a column named data that contains JSON data. To update a specific key in the JSON data, you can use the following query:

1
2
3
UPDATE my_table
SET data = JSON_SET(data, '$.key', 'new value')
WHERE <condition>;


In the above query, JSON_SET() is used to update a specific key ($.key) in the data column. The updated value is set to 'new value'. You need to replace <condition> with the appropriate condition to identify the row you want to update.


If you want to update multiple keys in the JSON data, you can chain multiple JSON_SET() functions like this:

1
2
3
UPDATE my_table
SET data = JSON_SET(JSON_SET(data, '$.key1', 'new value 1'), '$.key2', 'new value 2')
WHERE <condition>;


In this case, both 'key1' and 'key2' in the data column will be updated with their respective new values.


Note that if the JSON key you want to update does not exist in the data column, JSON_SET() will add it to the JSON data.


Remember to replace my_table, data, <condition>, 'key', and 'new value' with your actual table name, column name, condition, key to update, and new value.