Mysql Json 使用条件过滤器提取

Mysql Json extract with conditional filter

我正在尝试通过过滤器查询一些 json 数据。给定一个像这样的 json 数组:

[ {name:'name1', country:[{name:'France', people:10}, {name:'Japan',people:20}]}, {name:'name2', country:[{name:'France', people:20}, {name:'Japan',people:40}]}]

我想 select 所有具有国家名称 'France' 且值大于 10 的行作为 'people' 仅在具有 [=29= 的对象中] 名称设置为 'France'.

是否可以通过 Mysql JSON 函数实现?

非常感谢

首先,那是无效的 JSON,因此 MySQL 中 JSON 函数的 none 将起作用。在有效的 JSON 中,您不能像 ' 一样使用 single-quotes 来分隔键或字符串。您必须像 ".

一样使用 double-quotes

键也必须用 double-quotes 分隔,而不仅仅是值。

因此您的数据应如下所示:

[
  {
    "name": "name1",
    "country": [
      {
        "name": "France",
        "people": 10
      },
      {
        "name": "Japan",
        "people": 20
      }
    ]
  },
  {
    "name": "name2",
    "country": [
      {
        "name": "France",
        "people": 20
      },
      {
        "name": "Japan",
        "people": 40
      }
    ]
  }
]

如果我们将它加载到 table:

create table mytable (id serial primary key, data json);
insert into mytable set data = '...JSON based on the above...';

然后我们可以使用MySQL8.0的JSON_TABLE()函数:

select mytable.id, j.* 
from mytable, json_table(mytable.data, '$[*]' columns (
  name varchar(20) path '$.name',
  nested path '$.country[*]' columns (
    country_name varchar(20) path '$.name', 
    country_people int path '$.people')
  )
) as j

输出:

+----+-------+--------------+----------------+
| id | name  | country_name | country_people |
+----+-------+--------------+----------------+
|  1 | name1 | France       |             10 |
|  1 | name1 | Japan        |             20 |
|  1 | name2 | France       |             20 |
|  1 | name2 | Japan        |             40 |
+----+-------+--------------+----------------+

然后我们就可以像正常一样搜索了table:

select mytable.id, j.*
from mytable, json_table(mytable.data, '$[*]' columns (
  name varchar(20) path '$.name',
  nested path '$.country[*]' columns (
    country_name varchar(20) path '$.name',
    country_people int path '$.people')
  )
) as j
where j.country_name = 'France' and j.country_people = 10;

+----+-------+--------------+----------------+
| id | name  | country_name | country_people |
+----+-------+--------------+----------------+
|  1 | name1 | France       |             10 |
+----+-------+--------------+----------------+