当前位置: 代码网 > it编程>编程语言>Javascript > MySQL进行JSON复杂查询的完全指南

MySQL进行JSON复杂查询的完全指南

2025年07月01日 Javascript 我要评论
一、json对象全等判断:当强迫症遇到数据结构1.1 精确匹配(键顺序敏感)-- 案例:查找配置完全相同的设备(键顺序必须一致)select * from device_configs where c

一、json对象全等判断:当强迫症遇到数据结构

1.1 精确匹配(键顺序敏感)

-- 案例:查找配置完全相同的设备(键顺序必须一致)
select * from device_configs 
where config_json = '{"resolution": "1080p", "brightness": 80}';

-- 陷阱警告:以下两个json会被认为不同(键顺序不同)
'{"a":1, "b":2}' vs '{"b":2, "a":1}'

1.2 松散全等判断(键顺序无关)

-- 方法:使用json_contains双向包含 + 长度相同
select * from device_configs 
where 
  json_contains(config_json, '{"brightness": 80, "resolution": "1080p"}') 
  and 
  json_contains('{"brightness": 80, "resolution": "1080p"}', config_json)
  and
  json_length(config_json) = 2; -- 确保没有多余字段

二、数组的“灵魂拷问”式查询

2.1 数组完全相等(顺序敏感)

-- 查找tags数组严格等于["vip","北京"]的用户(顺序、数量、元素完全一致)
select * from users 
where tags_json = cast('["vip","北京"]' as json);

2.2 数组包含所有元素(顺序无关)

-- 查找tags包含"vip"和"北京"的用户(类似and条件)
select * from users 
where 
  json_contains(tags_json, '"vip"') 
  and 
  json_contains(tags_json, '"北京"');

2.3 数组包含任意元素(类似or条件)

-- 查找tags包含"vip"或"北京"的用户
select * from users 
where 
  json_contains(tags_json, '["vip"]') 
  or 
  json_contains(tags_json, '["北京"]');

三、嵌套结构的“掘地三尺”查询

3.1 多层级路径查询

-- 查找住在"北京朝阳区"的用户(嵌套对象查询)
select * from users 
where address_json->>'$.city' = '北京' 
  and address_json->>'$.district' = '朝阳区';

3.2 通配符搜索所有层级

-- 查找任意层级包含"error_code":500的日志(递归搜索)
select * from service_logs 
where json_search(log_json, 'all', '500', null, '$**.error_code') is not null;

3.3 深度过滤数组对象

-- 查找订单中有商品id=100且数量>2的订单(数组对象过滤)
select * from orders 
where json_exists(
  items_json, 
  '$[*]?(@.product_id == 100 && @.quantity > 2)'
);

四、混合条件综合查询

4.1 json字段 + 关系字段联合查询

-- 查找2023年后注册,且扩展信息中device_type="ios"的用户
select * from users 
where 
  register_time > '2023-01-01' 
  and 
  ext_info->>'$.device_type' = 'ios';

4.2 多json字段关联查询

-- 查找购物车总价>1000且包含"急件"标签的订单
select * from orders 
where 
  cast(cart_info->>'$.total_price' as decimal) > 1000 
  and 
  json_contains(tags_json, '"急件"');

4.3 动态条件生成查询

-- 根据前端传入的json过滤条件动态查询(php示例)
$filters = '{"status":"pending","price":{"$gt":100}}';
$where = [];
foreach(json_decode($filters, true) as $key => $value){
  if(is_array($value)){
    $where[] = "data_json->>'$.$key' > ".$value['$gt'];
  }else{
    $where[] = "data_json->>'$.$key' = '$value'";
  }
}
$sql = "select * from products where ".implode(' and ', $where);

五、性能优化黑科技

5.1 虚拟列 + 索引加速

-- 为常用查询条件创建虚拟列索引
alter table users 
add column city varchar(20) 
  generated always as (address_json->>'$.city'),
add index idx_city (city);

5.2 函数索引(mysql 8.0+)

-- 直接为json路径表达式创建索引
create index idx_price on products ((cast(data_json->>'$.price' as decimal)));

5.3 查询重写优化

-- 原查询(性能差)
select * from logs 
where json_extract(log_data, '$.request.time') > '2023-01-01';

-- 优化后(提取时间到独立字段 + 索引)
alter table logs add column request_time datetime 
  generated always as (json_unquote(json_extract(log_data, '$.request.time')));
create index idx_request_time on logs(request_time);

六、经典踩坑案例

6.1 隐式类型转换陷阱

-- 错误:字符串与数字比较导致索引失效
select * from products 
where data_json->>'$.id' = 100; -- $.id值是字符串"100"

-- 正确:显式类型转换
select * from products 
where cast(data_json->>'$.id' as unsigned) = 100;

6.2 通配符滥用灾难

-- 错误:左模糊查询全表扫描
select * from articles 
where content_json->>'$.text' like '%重要通知%';

-- 正确:使用全文索引或专用搜索引擎(如elasticsearch)

6.3 大json修改雪崩

-- 错误:频繁更新大json字段导致io飙升
update user_activities 
set log_json = json_array_append(log_json, '$', '新事件') 
where user_id = 1001;

-- 正确:拆分成关系表或分片存储

七、超硬核面试题

题目:如何高效实现json数组的交集查询?

示例:查找tags数组同时包含["vip","北京","90后"]的用户

参考答案

-- 方法1:json_contains链式调用
select * from users 
where 
  json_contains(tags_json, '"vip"') 
  and json_contains(tags_json, '"北京"')
  and json_contains(tags_json, '"90后"');

-- 方法2:利用json_table展开后统计(mysql 8.0+)
select user_id 
from users, json_table(
  tags_json,
  '$[*]' columns(tag varchar(10) path '$')
) as tags 
where tag in ('vip', '北京', '90后')
group by user_id
having count(distinct tag) = 3;

到此这篇关于mysql进行json复杂查询的完全指南的文章就介绍到这了,更多相关mysql json查询内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

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

发表评论

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