MySQL查询中的WHERE IN语句用于JSON数组。

huangapple go评论105阅读模式
英文:

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)
)

DB<>Fiddle

英文:

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(&#39;{&quot;sp_id&quot;: [1, 2, 113], &quot;spd_id&quot;: [], &quot;spclg_id&quot;: []}&#39;, &#39;1&#39;, &#39;$.sp_id&#39;) -- true
OR    JSON_CONTAINS(&#39;{&quot;sp_id&quot;: [1, 2, 113], &quot;spd_id&quot;: [], &quot;spclg_id&quot;: []}&#39;, &#39;9&#39;, &#39;$.sp_id&#39;) -- 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, &#39;$.sp_id[*]&#39; COLUMNS(
        val INT PATH &#39;$&#39;
    )) AS x
    WHERE val IN (1, 9)
)

DB<>Fiddle

huangapple
  • 本文由 发表于 2023年5月25日 21:32:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/76332882.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定