英文:
MySQL query WHERE IN for json array
问题
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)))
英文:
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)))
答案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)
)
英文:
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)
)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论