I have a MySQL 5.7 database with a JSON column containing an array of strings.
I need to remove a varying number of those strings from the array, by value, in one query.
Example JSON:
["1-1-2", "1-1-3", "1-2-2", "1-2-3", "1-1-16", "1-1-17"]
I may need to remove "1-1-16" and "1-1-17" so I end up with:
["1-1-2", "1-1-3", "1-2-2", "1-2-3"]
At other times, I may need to remove just one value, or several more, in one query.
JSON_REMOVE()
can accept multiple path arguments, but the problem is that when multiple paths are specified, the result of JSON_REMOVE()
is passed sequentially left to right on each path, which makes it very difficult to use the result of JSON_SEARCH()
for each passed path.
For example, this does not work, because the 2nd JSON_SEARCH will return the incorrect index for '1-1-17'
after '1-1-16'
has been removed:
UPDATE json_meta
SET document =
JSON_REMOVE( document,
JSON_UNQUOTE(JSON_SEARCH(document, 'one', '1-1-16')),
JSON_UNQUOTE(JSON_SEARCH(document, 'one', '1-1-17')),
)
WHERE id=10
You need to do this instead:
UPDATE json_meta
SET document =
JSON_REMOVE( document,
JSON_UNQUOTE(JSON_SEARCH(document, 'one', '1-1-16')),
JSON_UNQUOTE(JSON_SEARCH(JSON_REMOVE( document,
JSON_UNQUOTE(JSON_SEARCH(document, 'one', '1-1-16'))), 'one', '1-1-17'))
)
WHERE id=10
The query grows exponentially complex with each additional string that needs to be removed.
I'm wondering if the best solution would just be to use a chained REPLACE()
with all permutations of commas on each string (i.e. each string with a comma before, a comma after, a comma both before and after).
Final note: I found another question with the exact same issue described here. However, that question doesn't have an accepted answer, and the one answer there is very complex. That answer indicates that MySQL 5.6 doesn't have much JSON support; I am wondering, since I'm using MySQL 5.7, is there a simpler solution possible?