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查询内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论