Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

You can use the JSON_REMOVE function in MySQL to remove items from a JSON array that do not contain specific string values. Here is an example:

Assuming you have the following JSON array stored in a MySQL table:

[
   {"name": "Alice", "age": 25},
   {"name": "Bob", "age": 30},
   {"name": "Charlie", "age": 20},
   {"name": "David", "age": 35}
]

If you want to remove all items from the array that do not have the name "Bob", you can use the following SQL query:

UPDATE my_table SET my_column = JSON_REMOVE(my_column, REPLACE(JSON_SEARCH(my_column, 'one', 'Bob', NULL, '$[*]."name"'), '.name', ''))
WHERE JSON_CONTAINS(my_column, '"Bob"', '$[*]."name"') = 0;

This query uses the JSONSEARCH function to find the index of the item in the array that has the name "Bob", and then uses the JSONREMOVE function to remove all other items from the array. The WHERE clause filters out rows that do not contain the name "Bob" in any of the items in the array.