0

I have a mysql table "tbl1" with a JSON field "numbers" containing values like this:

{ "start" : ["101","102","104"], "final" : ["102","105","106"] }

How can i update "numbers" to remove a specific element (i.e. "102") from "start" and "final" ?

I know i have to use a combination of JSON_REMOVE and JSON_SEARCH but i don't find the solution.

5
  • No sorry. I want to delete only one element from a property value and not all the property. Commented May 29, 2020 at 10:07
  • Misread your question, but this should help you stackoverflow.com/questions/40497905/… Commented May 29, 2020 at 10:14
  • What is your MySQL version? Commented May 29, 2020 at 10:16
  • mysql Ver 14.14 Distrib 5.7.30 Commented May 29, 2020 at 10:52
  • I find a solution with a query like this: update tbl1 set numbers = JSON_REMOVE(numbers, JSON_UNQUOTE(JSON_SEARCH(numbers, 'one', '102',NULL,'$.start'))) where JSON_SEARCH(numbers, 'one', '102',NULL,'$.start') is not null; Commented May 29, 2020 at 11:16

1 Answer 1

1
WITH RECURSIVE
cte AS ( SELECT JSON_REMOVE(json_field, JSON_UNQUOTE(JSON_SEARCH(json_field, 'one', '102'))) json_field
         FROM source_table
         UNION ALL
         SELECT JSON_REMOVE(json_field, JSON_UNQUOTE(JSON_SEARCH(json_field, 'one', '102'))) json_field
         FROM cte
         WHERE JSON_SEARCH(json_field, 'one', '102') )
SELECT json_field
FROM cte
WHERE JSON_SEARCH(json_field, 'one', '102') IS NULL;

and respectively

UPDATE source_table
JOIN (  WITH RECURSIVE
        cte AS ( SELECT id, JSON_REMOVE(json_field, JSON_UNQUOTE(JSON_SEARCH(json_field, 'one', '102'))) json_field
                 FROM source_table
                 UNION ALL
                 SELECT id, JSON_REMOVE(json_field, JSON_UNQUOTE(JSON_SEARCH(json_field, 'one', '102'))) json_field
                 FROM cte
                 WHERE JSON_SEARCH(json_field, 'one', '102') )
        SELECT id, json_field
        FROM cte
        WHERE JSON_SEARCH(json_field, 'one', '102') IS NULL
     ) processed USING (id)
SET source_table.json_field = processed.json_field;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.