在MySQL5.7中查询JSON整数数组中是否存在值

tzdcorbm  于 2022-12-10  发布在  Mysql
关注(0)|答案(2)|浏览(667)

我有一个MySQL5.7表,如下所示:
Id|meta

1|空
2|{“grant_ids”:[5,7]}
我想查询META->GRANT_ID中值为5的行。我试过了

select *   from content.banners where meta->>"$.grant_ids" in (5);

但这不管用。我不认为in是受支持的,但是你知道如何实现这个查询吗?

toiithl6

toiithl61#

mysql> create table table_that_looks_like_this ( 
  id int primary key, meta json);

mysql> insert into table_that_looks_like_this values
    -> (1, null),
    -> (2, '{"grant_ids": [5, 7]}'),
    -> (3, '{"grant_ids": [4, 8]}'),
    -> (4, '{"no_grant_ids": [5, 7]}');

mysql> select * from table_that_looks_like_this 
 where json_contains(meta, '[5]', '$.grant_ids');
+----+-----------------------+
| id | meta                  |
+----+-----------------------+
|  2 | {"grant_ids": [5, 7]} |
+----+-----------------------+

DBFiddle
JSON_EXTRACT()将只返回您给出的路径上的JSON数组,并且数组不是标量值5。用->>操作符取消对JSON数组的引用没有任何效果;“未加引号的”JSON数组是完全相同的数组。

kse8i1jr

kse8i1jr2#

您可以这样编写它,使用SQL的json函数。

SELECT*FROM CONTENT.BANNERS b WHERE JSON_EXTRACT(b.meta,“$.grant_ids”)in(5)

相关问题