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.
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2023-04-29 00:34:12 +0000
Seen: 9 times
Last updated: Apr 29 '23
How to deal with an operational error when connecting Django to MySQL?
In this scenario, what is the reason for the WHERE clause in MySQL to produce zero rows?
How can multiple queries be merged into a single stored procedure in MySQL?
What is the method for verifying the existence of a mysql database?
What does "waiting for handler commit" mean in relation to the slow writes experienced in MySQL 8?
What is the process for implementing a Many to Many relationship using NestJs Sequlize and Mysql2?
How can Spring Boot and Mysql be utilized for CRUD operations?
How can I refine the results for a specific column in MySQL?