7

I'm still pretty new to handling JSON fields in MySQL. All the solutions I've come across deal with objects that have key/values; unable to find one that handles JSON arrays.

Anyways, what I want to do is to be able to select all rows where the interestIds contain 2 in them. How do I do that? Thanks.

Users table

+----+-------------+
| id | interestIds |
+----+-------------+
|  1 | [1, 2]      |
|  2 | [3, 2]      |
|  3 | [2, 4]      |
+----+-------------+

Sample test query:

SET @userId = 2;
SELECT * FROM Users
WHERE @userId IN JSON_CONTAINS(@user, interestIds, '$[1]');

I am confused as how to use the JSON_* functions; not sure what to put for the 3rd parameter...

4 Answers 4

5

You can use the following solution, using JSON_CONTAINS:

SELECT * 
FROM Users
WHERE JSON_CONTAINS(interestIds, '2') = 1;

The third (optional) paramater path gives you the posibility to use this function only on a specific part of your JSON value. So the following example checks if 2 is the second value of the array:

SELECT *
FROM test
WHERE JSON_CONTAINS(interestIds, '2', '$[1]') = 1;

demo on dbfiddle.uk

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

Comments

4

Use JSON_SEARCH which returns path to element you are searching, or null if not found:

SELECT *
FROM users
WHERE JSON_SEARCH(interestids, 'one', '2') IS NOT NULL

Live Demo

If you're storing many-to-many relationship using simple JSON array, there are better ways to do it. Consider creating user_interest table and doing it the right and simpler way. That is if your JSON actually looks like you have shown us and does not contain dynamic key-value pairs.

1 Comment

The question contains JSON where the interestIds are array of integers not strings. JSON_SEARCH does not work on integers
1
SQL> select id 
from users 
where JSON_CONTAINS(interestIds, "2","$");
+----+
| id |
+----+
|  1 |
|  2 |
|  3 |
+----+
3 rows in set (0.0015 sec)

Comments

0

Wrap your select to JSON_ARRAYAGG

Like:

SELECT JSON_ARRAYAGG(JSON_OBJECT(....)) FROM table.... 

1 Comment

only suppor above 5.7.22

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.