How to remove a number from MySQL's JSON array?

邮差的信 提交于 2021-02-19 00:49:46

问题


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
  1. json_search returns the path of where the value is, ie. "$[0]"
  2. replace remove the " otherwise an error will occur with json_remove
  3. json_remove will remove the path from the json_search result

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!