简单谈谈MySQL5.7 JSON格式检索
作者:yangfei001 时间:2024-01-22 09:07:03
MySQL5.7版本开始支持JSON格式,在创建表时,可以指定列表的数据类型为JSON,但是如何在JSON格式上创建索引呢??
本人做了一个简单测试。
第一步:建立一个包含JSON类型的表:
CREATE TABLE json_test` (
id` int (8) NOT NULL AUTO_INCREMENT,
content` json NOT NULL ,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
第二步:初始化数据
insert into json_test(content) value( '{"name":"zhangsan","age":18}' );
insert into json_test(content) value( '{"name":"lisi","age":19}' );
insert into json_test(content) value( '{"name":"wangwu","age":20}' );
第三步:查询JSON类列的数据
select json_extract(content, '$.name' ) from json_test where json_extract(content, '$.name' )= "zhangsan" ;
通过expain分析改查询语句,发现其走全表扫描
在网上查询资料,得知如果要在JSON列上进行检索,需要对检索的key创建虚拟列,然后再虚拟列上创建索引
第四步:在content列上,对"name"建立虚拟列
ALTER TABLE json_test ADD name_virtual varchar (32) GENERATED ALWAYS AS (json_extract(content, '$.name' )) VIRTUAL;
第五步:对虚拟列创建索引
CREATE INDEX name_virtual_index ON json_test(name_virtual);
再次做查询( 注,where条件需要使用虚拟列来进行检索,如果直接用JSON列比较,还是会走全表扫描 )
explain select json_extract(content, '$.name' ) from json_test where name_virtual= "zhangsan" \G
总结:
其实MySQL通过一种空间换时间的做法,类似创建一个触发器,把JSON列上的数据冗余存储到虚拟列上,比较的时候通过走虚拟列的索引,再定位到实际数据。
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python 实现数据结构-堆栈和队列的操作方法
Python 模拟员工信息数据库操作的实例
![](https://img.aspxhome.com/file/2023/5/79635_0s.jpg)
安全地关闭MySQL服务的教程
python可以美化表格数据输出结果的两个工具
Django自定义全局403、404、500错误页面的示例代码
Python中url标签使用知识点总结
![](https://img.aspxhome.com/file/2023/5/79465_0s.png)
Python机器学习之KNN近邻算法
![](https://img.aspxhome.com/file/2023/7/75297_0s.png)
自然描述与自然任务
![](https://img.aspxhome.com/file/UploadPic/20101/26/pic0-99s.jpg)
Numpy 理解ndarray对象的示例代码
![](https://img.aspxhome.com/file/2023/7/62607_0s.png)
oracle中添加删除主键的方法
vue element-ul实现展开和收起功能的实例代码
![](https://img.aspxhome.com/file/2023/7/122997_0s.png)
python离散建模之感知器学习算法
Javascript类型系统之undefined和null浅析
菜鸟大讲堂:如何查看mysql版本的四种方法
element 实现导航栏收起展开功能及思路
![](https://img.aspxhome.com/file/2023/4/126484_0s.gif)
JavaScript中call,apply,bind的区别与实现
![](https://img.aspxhome.com/file/2023/1/136021_0s.png)
详解python string类型 bytes类型 bytearray类型
JS 中如何判断 null
Python通用验证码识别OCR库之ddddocr验证码识别
![](https://img.aspxhome.com/file/2023/4/126914_0s.jpg)
Python 代码实现各种酷炫功能
![](https://img.aspxhome.com/file/2023/3/134723_0s.png)