Skip to content
Advertisement

MySQL how to search a JSON field for all rows that intersect with JSON values

Assume that I have a MySQL table with a JSON field, with the structure & values shown below:

I would like to get all rows that have ANY of the JSON values that match in a SELECT query.

For example:

This yields 2 rows:

However, I would like it to yield all of the rows, because every row has at least a “1” or a “2” in the JSON. In other words, I’m looking for a query that will return rows where the JSON intersection is non-empty.

Thus, I WANT it to return:

Please ignore the larger question of whether it’s even a good idea to use JSON fields over foreign keys, etc. Assume that I have to use a JSON field.

Advertisement

Answer

OR is the simplest method:

But if you want to pass in the JSON array, use JSON_OVERLAPS():

Here is a db<>fiddle.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement