1

Our database solution is very JSON heavy, and as such, our SQL queries are all JSON based (for the most part). This includes extensive use of JSON_ARRAYAGG().

The problem I'm encountering is using a returned array of indexes in WHERE IN, which simply doesn't work. From what I can tell it's a simple formatting issue where MySQL wants an () encapsulation and a JSON array is a [] encapsulation.

For example:

SELECT COUNT(si.ID) AS item_count, JSON_ARRAYAGG(si.ID) AS item_array
FROM sourcing_item si;

Returns:

7, [1,2,3,4,5,6,7]

What I need to do is write a complex nested query that allows for selecting record IDs that are IN the JSON_ARRAYAGG result. Like:

SELECT si.item_name
FROM sourcing_item si
WHERE si.ID IN item_array

Of course the above doesn't work because MySQL doesn't recognize [] vs. ().

Is there a viable workaround for this issue? I'm surprised they haven't updated MySQL to allow the WHERE IN clause to work with a JSON array...

1 Answer 1

2

The MEMBER OF operator does this.

SELECT si.item_name
FROM sourcing_item si
WHERE si.ID MEMBER OF (item_array)
Sign up to request clarification or add additional context in comments.

12 Comments

It's relatively new, it was added in MySQL 8.0.
If you have a subquery, why do you need to use JSON_ARRAYAGG()? Just use WHERE sp.sourcing_search_ref_id IN (SELECT ss.ID FROM ...)
Try using JOIN instead of IN. That will allow you to pass multiple columns up.
All those nested INs should just be a join between all 3 tables.
In general, SELECT * FROM A WHERE A.col1 IN (SELECT col2 FROM B) can be transformed to SELECT A.* FROM A JOIN B ON A.col1 = B.col2
|

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.