问题
If I have a MySQL table with a JSON column called numbers and a record that has [1, 2, 3] in that column (array of integers), how do I update that record to remove the 2 (so it becomes [1, 3])?
回答1:
I was searching for an answer my self and came to this question, not wanting to use objects I continued the search. But I found a solution, you need to use a combination of json_remove and json_search
The following removes the value 1 from the table tbl and the column numbers
UPDATE tbl
SET numbers = JSON_REMOVE(
numbers, replace(json_search(numbers, 'one', 1), '"', '')
)
WHERE json_search(numbers, 'one', 1) IS NOT NULL
json_searchreturns the path of where the value is, ie."$[0]"replaceremove the"otherwise an error will occur withjson_removejson_removewill remove the path from thejson_searchresult
Et voila, your value is removed.
Note: this assumes no duplicate values
回答2:
Until someone finds a better solution, I just converted it to an object instead: {"1": 1, "2": 2, "3": 3}. Yes, this is uglier and occupies more disk space, but you get the benefit of not having to worry about duplicates.
To add a number:
update tbl set numbers = json_insert(`numbers`, '$."4"', 4);
To remove a number:
update tbl set numbers = json_remove(`numbers`, '$."4"');
To get the row with a certain number:
select * from tbl where json_contains_path(`numbers`, 'one', '$."4"');
来源:https://stackoverflow.com/questions/40497905/how-to-remove-a-number-from-mysqls-json-array