mysql JSON路径遍历数组的语法正确吗?

toiithl6  于 9个月前  发布在  Mysql
关注(0)|答案(2)|浏览(83)

我的问题是关于在mysql的JSON数据类型中搜索时搜索json数组的内容。

数据库结构

所以,如果我在mysql表中有两行,有一个json字段,名为foo
第一行有:

{
  "items": [
    {"type": "bar"}
  ]
}

字符串
第二行有:

{
  "items": [
    {"type": "baz"}
  ]
}

Things that work

我能跑

select `foo`->"$.items[0].type" from `jsontest`


返回两个结果:barbaz
我能跑

select `id` from `jsontest` where `foo`->"$.items[0].type" = "bar"


返回1个结果:1-即第一行的id。

问题

mysql文档指出,您可以使用[*]来“计算JSON数组中所有元素的值”。
但是,以下查询返回零项:

select `id` from `jsontest` where `foo`->"$.items[*].type" = "bar"


我的查询有什么问题?

rjzwgtxy

rjzwgtxy1#

执行以下查询:

select id, `foo`->"$.items[*].type[0]" from `jsontest`;

字符串
您会注意到返回值显示为“[bar]",这是JSON数组。

select * from `jsontest` 
where `foo`->"$.items[*].type" = JSON_ARRAY('bar');


无论如何,下面的查询也应该起作用:

select id from `jsontest` where JSON_SEARCH(`foo`, 'all','bar') is not null;

sc4hvdpw

sc4hvdpw2#

我想你想要:

SELECT `id` FROM `jsontest` WHERE JSON_CONTAINS(`foo`->"$.items[*].type", '"bar"', '$')

字符串

相关问题