0

I have saved data for a column in json form:

{"sp_id": [1, 2,113],"spd_id": [],"spclg_id": []}

I would like to use WHERE IN to check if the sp_id field contains the values ​​specified in the array

i.e. I want to check whether there is at least one occurrence of the given values ​​in the u_id array.

  • At least one element for sp_id must match
  • must be in mysql
  • mysql version: 5.7.40

in php it would look like this:

if(count(array_intersect($needle, $haystack)))
11
  • There is no u_id in your JSON, which makes your question rather unclear. Commented May 25, 2023 at 13:35
  • corrected, sorry :) Commented May 25, 2023 at 13:37
  • Please share more details, like the table structure, sample input data, the expected output, and your attempts to resolve the problem Commented May 25, 2023 at 13:38
  • 1
    Think you are looking for dev.mysql.com/doc/refman/8.0/en/… Commented May 25, 2023 at 13:51
  • 2
    Out of curiosity, why did you store these data in JSON? It would have been easy to query if you had stored multi-valued attributes as normal rows and columns. Commented May 25, 2023 at 14:11

1 Answer 1

0

You can use JSON_CONTAINS function which, unfortunately, has some limitations. You need to check items one by one:

-- e.g. when you need to check if [1, 9] intersects

WHERE JSON_CONTAINS('{"sp_id": [1, 2, 113], "spd_id": [], "spclg_id": []}', '1', '$.sp_id') -- true
OR    JSON_CONTAINS('{"sp_id": [1, 2, 113], "spd_id": [], "spclg_id": []}', '9', '$.sp_id') -- false

The better solution is to use JSON_TABLE which requires MySQL 8 or later:

SELECT *
FROM t
WHERE id IN (
    SELECT id
    FROM JSON_TABLE(t.json, '$.sp_id[*]' COLUMNS(
        val INT PATH '$'
    )) AS x
    WHERE val IN (1, 9)
)

DB<>Fiddle

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

7 Comments

only I can have a lot of these values, that's why I wanted to avoid using JSON_CONTAINS... And what would the use of OPENJSON look like? I can't find this function in the documentation, this function is available for mysql?
Sorry it was JSON_TABLE dev.mysql.com/doc/refman/8.0/en/json-table-functions.html, but your hands are tied. JSON_SEARCH can do exact match of [1], [1, 2], [1, 2, 113] but not [1, 9].
We are currently planning to upgrade the company
You will show me what JSON_TABLE will look like in my case?
I'd rather not store the data as json if it is used in where clause.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.