0
set @a = '["1","2","3"]';
set @b = '["4","2","3"]';

I have two json arrays. Now I want to remove all the elements from @b from @a if it exists. else ignore.

Expected result:

["1"]

We can loop through @b and remove one by one from @a.

But I am looking for a best solution.

Is there somthing like JSON_REMOVE_ALL();

1 Answer 1

1

The following uses JSON functions to extract elements in @a that are not in @b.

  • JSON_TABLE is used to convert @a into a table before
  • JSON_CONTAINS is used to check whether the element in @a exists in @b.
  • Finally JSON_ARRAYAGG aggregates the results into a single json array value

Schema (MySQL v8.0)


Query #1

set @a = cast('["1","2","3"]' as json);

There are no results to be displayed.


Query #2

set @b = cast('["4","2","3"]' as json);

There are no results to be displayed.


Query #3

SELECT
    JSON_ARRAYAGG(num) result 
FROM
    JSON_TABLE(@a,"$[*]" COLUMNS(num json PATH "$" )) ta
WHERE JSON_CONTAINS(@b,num,'$')=0;
result
["1"]

View on DB Fiddle

Sign up to request clarification or add additional context in comments.

1 Comment

I had to replace the last line with WHERE JSON_CONTAINS(@b,JSON_ARRAY(num),'$')=0; in 8.0.40

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.