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

时间:2016-07-29 11:33:33

标签: mysql mysql-json

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

数据库结构

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

第一行有:

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

第二行有:

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

有效的东西

我可以跑

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

返回2个结果:barbaz

我可以跑

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

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

我的问题

您可以[*]使用mysql docs state来评估JSON数组中所有元素的值"。

但是,以下查询返回零项:

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

我的查询有什么问题?

1 个答案:

答案 0 :(得分:8)

进行以下查询:

buttons

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

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

无论如何,以下查询也应该有效:

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