当前位置: 代码网 > it编程>编程语言>Javascript > MySQL JSON 查询中的对象与数组技巧及查询示例

MySQL JSON 查询中的对象与数组技巧及查询示例

2025年06月11日 Javascript 我要评论
mysql 中 json 对象和 json 数组查询的详细介绍及带有 where 条件的查询示例:json 对象查询1. json_contains用于检查 json 对象是否包含指定的值或 json

mysql 中 json 对象和 json 数组查询的详细介绍及带有 where 条件的查询示例:

json 对象查询

1. json_contains

用于检查 json 对象是否包含指定的值或 json 对象。

  • 语法json_contains(json_doc, val[, path])
  • 示例: 假设有一个表 person,其中有一个 json 列 info,存储了个人信息。
create table person (
    id int primary key,
    info json
);
insert into person (id, info) values (1, '{"name": "张三", "age": 30}');

查询 info 列中 name"张三" 的记录:

select * from person where json_contains(info, '"张三"', '$.name');

如果 info 列中包含 {"name": "张三"},则返回对应的行。

2. json_extract

用于从 json 对象中提取指定路径的值。

  • 语法json_extract(json_doc, path)
  • 示例: 查询 info 列中 age 大于 25 的记录
select * from person where json_extract(info, '$.age') > 25;

通过提取 age 的值并进行比较,筛选出符合条件的记录。

3. json_table

将 json 对象转换为关系型表格,便于查询。

语法

json_table(
    json_doc,
    path_expression
    columns(
        column_name column_type path json_path [on_empty] [on_error],
        ...
    )
) [as] alias

示例

select *
from person,
json_table(
    info,
    '$' columns(
        name varchar(50) path '$.name',
        age int path '$.age'
    )
) as jt
where jt.age > 25;

info 列中的 json 数据转换为表格格式,然后通过 where 条件筛选出 age 大于 25 的记录。

json 数组查询

1. json_contains

同样适用于 json 数组,检查数组是否包含指定的值。

  • 语法json_contains(json_array, val[, path])
  • 示例: 假设有一个表 fruits,其中有一个 json 列 fruits_array,存储了水果数组
create table fruits (
    id int primary key,
    fruits_array json
);
insert into fruits (id, fruits_array) values (1, '["apple", "banana", "orange"]');

查询 fruits_array 列中包含 "banana" 的记录

select * from fruits where json_contains(fruits_array, '"banana"');

如果 fruits_array 中包含 "banana",则返回对应的行。

2. json_extract

从 json 数组中提取指定索引的值。

  • 语法json_extract(json_array, path)
  • 示例: 查询 fruits_array 列中第二个水果为 "banana" 的记录
select * from fruits where json_extract(fruits_array, '$[1]') = '"banana"';

通过提取数组中索引为 1 的值并进行比较,筛选出符合条件的记录。

3. json_table

将 json 数组转换为关系型表格。

语法

json_table(
    json_doc,
    path_expression
    columns(
        column_name column_type path json_path [on_empty] [on_error],
        ...
    )
) [as] alias

示例

select *
from fruits,
json_table(
    fruits_array,
    '$[*]' columns(
        fruit varchar(50) path '$'
    )
) as jt
where jt.fruit = 'banana';

fruits_array 列中的 json 数组转换为表格格式,然后通过 where 条件筛选出包含 "banana" 的记录。

到此这篇关于mysql json 查询中的对象与数组技巧的文章就介绍到这了,更多相关mysql json查询内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com