【问题标题】:Correct syntax for mysql JSON path to traverse arrays?mysql JSON路径遍历数组的正确语法?
【发布时间】:2016-12-04 02:39:12
【问题描述】:

我的问题是关于在 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。

我的问题

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

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

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

我的查询有什么问题?

【问题讨论】:

    标签: mysql mysql-json


    【解决方案1】:

    进行以下查询:

    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;
    

    【讨论】:

    • 哇...我为此挣扎了一会儿。这应该是公认的答案。
    猜你喜欢
    • 2020-02-03
    • 1970-01-01
    • 2020-05-10
    • 1970-01-01
    • 2016-08-07
    • 1970-01-01
    • 2013-12-12
    • 2010-09-23
    相关资源
    最近更新 更多