0

I have two tables that look like this..

Baskets

id Array
1 ["Apple", "Mango", "Pineapple"]
2 ["Mango", "Pineapple"]
3 ["Dragonfruit"]

Stock

Fruit Count
Apple 100
Mango 500
Kiwi 99
Grapes 0

Through a SQL query, I have to check how many fruits from an array of the first table are present in the second table.

For example, out of ["Apple", "Mango", "Pineapple"] only Apple and Mango is in the Stock table.

Expected outcome:

id available
1 2
2 1
3 0

PS. this is a simplification of the actual problem I'm trying to solve, my main query is how to match a JSON array of objects against some other table. The fruits/stock example is just for explaining the problem.

3
  • Sounds like you should be using MongoDB instead of MySQL Commented Mar 16, 2021 at 10:51
  • That is not under my control. @Stewart Commented Mar 16, 2021 at 10:53
  • Mongo would be if you wanted to do it with JS and not learn the SQL which is pretty concise in the accepted answer and I bet many times faster. Commented Dec 7, 2023 at 4:50

1 Answer 1

2
SELECT Baskets.id, COUNT(Stock.Fruit) available
FROM Baskets 
LEFT JOIN Stock ON JSON_SEARCH(Baskets.Array, 'one', Stock.Fruit) IS NOT NULL
GROUP BY Baskets.id

https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=a0f8e8fba8851fcda508affca0201ba9

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.