MySQL5.7特性:JSON数据类型「建议收藏」

MySQL5.7特性:JSON数据类型「建议收藏」概述 MySQL5.7的发行声明中,官方称之为里程碑式的版本,除了运行速度大幅度提升之外,还添加了之前版本没有的功能,如本文所述的原生JSON数据类型功能。 在此版本之前,MySQL所有的JSON数…

MySQL5.7特性:JSON数据类型

什么是JSON类型

作为DBA,可能会对这个概念稍微有点陌生,但是对于开发者来说,这是一个十分熟悉的事物。

JSON(JavaScript Object Notation, JS 对象简谱) 是一种轻量级的数据交换格式。它基于 ECMAScript (欧洲计算机协会制定的js规范)的一个子集,采用完全独立于编程语言的文本格式来存储和表示数据。简洁和清晰的层次结构使得 JSON 成为理想的数据交换语言。 易于人阅读和编写,同时也易于机器解析和生成,并有效地提升网络传输效率。

MySQL原始JSON类型的优势在哪?

原生的JSON优势如下:

存储上类似text,可以存非常大的数据。

存储在JSON列中的JSON文档的自动验证 。无效的文档会产生错误。

优化的存储格式。存储在JSON列中的JSON文档将 转换为内部格式,以允许对文档元素进行快速读取访问。

相比于传统形式,不需要遍历所有字符串才能找到数据。

支持索引:通过虚拟列的功能可以对JSON中部分的数据进行索引。

MySQL的JSON类型

创建JSON类型表

创建一个基础的员工表,除了工号字段外,还有一个个人基础信息字段和一个个人能力信息字段

MySQL [test]> CREATE TABLE  employee (
    -> 
    ->     `empno` int(10) unsigned NOT NULL AUTO_INCREMENT,
    -> 
    ->     `basic_info` JSON NOT NULL,
    -> 
    ->     `skill_info` JSON NOT NULL,
    -> 
    ->     PRIMARY KEY (`empno`)
    -> 
    -> );
Query OK, 0 rows affected (0.02 sec)

代码100分

表的基础信息,其中JSON类型的字段,是不可以有默认值的,这点需要注意

代码100分MySQL [test]> desc employee;
+------------+------------------+------+-----+---------+----------------+
| Field      | Type             | Null | Key | Default | Extra          |
+------------+------------------+------+-----+---------+----------------+
| empno      | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| basic_info | json             | NO   |     | NULL    |                |
| skill_info | json             | NO   |     | NULL    |                |
+------------+------------------+------+-----+---------+----------------+
3 rows in set (0.00 sec)

试着插入几条数据

我们手动插入几条数据进这张表中,在前两条数据中,在个人能力信息上使用的是数组的方式,后面两条则是使用对象的形式。在MySQL5.7.8版本后的JSON类型中,这两种都是可以的。

INSERT INTO `employee`  VALUES (1,"{"name": "wangyiyi", "age": "23" ,"from": "hangzhou"}", "["java", "go", "python"]");

INSERT INTO `employee`  VALUES (2,"{"name": "linxue", "age": 24 ,"from": "shanghai"}", "["mysql", "oracle", "python"]");

INSERT INTO `employee`  VALUES (3,"{"name": "zhaoqing", "age": 24 ,"from": "shanghai"}", "{"system": "linux","database": "mysql", "language": "python"}");

INSERT INTO `employee`  VALUES (4,"{"name": "zhouxixi", "age": 30 ,"from": "nanjing"}", "{"system": ["linux","windows"],"database": ["mysql","oracle","postgresql"], "language": ["python","java","go"]}");

插入多个数据后,表中内容为如下

代码100分MySQL [test]> select * from employee;
+-------+-------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------+
| empno | basic_info                                            | skill_info                                                                                                            |
+-------+-------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------+
|     1 | {"age": "23", "from": "hangzhou", "name": "wangyiyi"} | ["java", "go", "python"]                                                                                              |
|     2 | {"age": 24, "from": "shanghai", "name": "linxue"}     | ["mysql", "oracle", "python"]                                                                                         |
|     3 | {"age": 24, "from": "shanghai", "name": "zhaoqing"}   | {"system": "linux", "database": "mysql", "language": "python"}                                                        |
|     4 | {"age": 30, "from": "nanjing", "name": "zhouxixi"}    | {"system": ["linux", "windows"], "database": ["mysql", "oracle", "postgresql"], "language": ["python", "java", "go"]} |
+-------+-------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------+
4 rows in set (0.00 sec)

json数据查询方式

在插入了json类型的数据之后,可以针对JSON类型做一些特定的查询,如查询年龄大于20的记录
在SQL的语句中使用 字段->键名 就可以查询出所对应的键值

MySQL [test]>  select * from employee  WHERE basic_info->"$.age"> 20;
+-------+-------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------+
| empno | basic_info                                            | skill_info                                                                                                            |
+-------+-------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------+
|     1 | {"age": "23", "from": "hangzhou", "name": "wangyiyi"} | ["java", "go", "python"]                                                                                              |
|     2 | {"age": 24, "from": "shanghai", "name": "linxue"}     | ["mysql", "oracle", "python"]                                                                                         |
|     3 | {"age": 28, "from": "shanghai", "name": "zhaoqing"}   | {"system": "linux", "database": "mysql", "language": "go"}                                                            |
|     4 | {"age": 30, "from": "nanjing", "name": "zhouxixi"}    | {"system": ["linux", "windows"], "database": ["mysql", "oracle", "postgresql"], "language": ["python", "java", "go"]} |
+-------+-------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------+
4 rows in set (0.00 sec)

MySQL [test]> select * from employee  WHERE basic_info->"$.age"< 20;
Empty set (0.00 sec)

除了使用上述方式外,也可使用 提取json值的 函数 json_extract (使用函数的方式)

MySQL [test]> select * from employee where json_extract(basic_info,"$.age") = 24;
+-------+-----------------------------------------------------+----------------------------------------------------------------+
| empno | basic_info                                          | skill_info                                                     |
+-------+-----------------------------------------------------+----------------------------------------------------------------+
|     2 | {"age": 24, "from": "shanghai", "name": "linxue"}   | ["mysql", "oracle", "python"]                                  |
|     3 | {"age": 24, "from": "shanghai", "name": "zhaoqing"} | {"system": "linux", "database": "mysql", "language": "python"} |
+-------+-----------------------------------------------------+----------------------------------------------------------------+
2 rows in set (0.00 sec)

对于数值查询也可做一个范围内查询,如下:

MySQL [test]> select * from employee  WHERE basic_info->"$.age" in (23, 24);
+-------+-------------------------------------------------------+----------------------------------------------------------------+
| empno | basic_info                                            | skill_info                                                     |
+-------+-------------------------------------------------------+----------------------------------------------------------------+
|     1 | {"age": "23", "from": "hangzhou", "name": "wangyiyi"} | ["java", "go", "python"]                                       |
|     2 | {"age": 24, "from": "shanghai", "name": "linxue"}     | ["mysql", "oracle", "python"]                                  |
|     3 | {"age": 24, "from": "shanghai", "name": "zhaoqing"}   | {"system": "linux", "database": "mysql", "language": "python"} |
+-------+-------------------------------------------------------+----------------------------------------------------------------+
3 rows in set, 1 warning (0.00 sec)

因为 JSON 不同于字符串,所以如果用字符串和 JSON 字段比较,是不会相等的;

如下,直接使用字符串查询,查询不出来内容

MySQL [test]> select * from employee where basic_info = "{"age": 24, "from": "shanghai", "name": "linxue"}";
Empty set (0.00 sec)

可以通过 CAST 将字符串转成 JSON 的形式,如下:

MySQL [test]> select * from employee where basic_info = CAST("{"age": 24, "from": "shanghai", "name": "linxue"}" AS JSON);
+-------+---------------------------------------------------+-------------------------------+
| empno | basic_info                                        | skill_info                    |
+-------+---------------------------------------------------+-------------------------------+
|     2 | {"age": 24, "from": "shanghai", "name": "linxue"} | ["mysql", "oracle", "python"] |
+-------+---------------------------------------------------+-------------------------------+
1 row in set (0.00 sec)

查看单纯数组类型的函数JSON_CONTAINS

MySQL [test]> select * from employee where JSON_CONTAINS (skill_info,""mysql"");
+-------+---------------------------------------------------+-------------------------------+
| empno | basic_info                                        | skill_info                    |
+-------+---------------------------------------------------+-------------------------------+
|     2 | {"age": 24, "from": "shanghai", "name": "linxue"} | ["mysql", "oracle", "python"] |
+-------+---------------------------------------------------+-------------------------------+
1 row in set (0.00 sec)

JSON_PRETTY函数: 以易于阅读的格式打印出JSON值。便于在一些外部应用引用数据时,更方便的使用它

MySQL [test]> select JSON_PRETTY(basic_info) from employee;
+---------------------------------------------------------------+
| JSON_PRETTY(basic_info)                                       |
+---------------------------------------------------------------+
| {
  "age": "23",
  "from": "hangzhou",
  "name": "wangyiyi"
} |
| {
  "age": 24,
  "from": "shanghai",
  "name": "linxue"
}     |
| {
  "age": 28,
  "from": "shanghai",
  "name": "zhaoqing"
}   |
| {
  "age": 30,
  "from": "nanjing",
  "name": "zhouxixi"
}    |
+---------------------------------------------------------------+
4 rows in set (0.00 sec)

MySQL 5.7.22中添加了此功能,此函数返回用于存储JSON文档的二进制表示的字节数,用于查看当前JSON字段的存储大小

MySQL [test]> select skill_info,JSON_STORAGE_SIZE(skill_info) AS Size  from employee;
+-----------------------------------------------------------------------------------------------------------------------+------+
| skill_info                                                                                                            | Size |
+-----------------------------------------------------------------------------------------------------------------------+------+
| ["java", "go", "python"]                                                                                              |   29 |
| ["mysql", "oracle", "python"]                                                                                         |   34 |
| {"system": "linux", "database": "mysql", "language": "go"}                                                            |   63 |
| {"system": ["linux", "windows"], "database": ["mysql", "oracle", "postgresql"], "language": ["python", "java", "go"]} |  137 |
+-----------------------------------------------------------------------------------------------------------------------+------+
4 rows in set (0.00 sec)

查询JSON字段的长度

MySQL [test]> select JSON_LENGTH(basic_info) from employee;
+-------------------------+
| JSON_LENGTH(basic_info) |
+-------------------------+
|                       3 |
|                       3 |
|                       3 |
|                       3 |
+-------------------------+
4 rows in set (0.00 sec)

查看数据的类型:可以是对象,数组或标量类型

MySQL [test]> select JSON_TYPE(skill_info) from employee;
+-----------------------+
| JSON_TYPE(skill_info) |
+-----------------------+
| ARRAY                 |
| ARRAY                 |
| OBJECT                |
| OBJECT                |
+-----------------------+
4 rows in set (0.00 sec)

json数据修改方式

如果是整个 json 更新的话,和一般类型插入是一样的

json_array_insert是在指定下标插入,这是插入一般数组类型时的操作

MySQL [test]> SELECT json_array_insert(skill_info, "$[1]", "php") from employee;
+-----------------------------------------------------------------------------------------------------------------------+
| json_array_insert(skill_info, "$[1]", "php")                                                                          |
+-----------------------------------------------------------------------------------------------------------------------+
| ["java", "php", "go", "python"]                                                                                       |
| ["mysql", "php", "oracle", "python"]                                                                                  |
| {"system": "linux", "database": "mysql", "language": "python"}                                                        |
| {"system": ["linux", "windows"], "database": ["mysql", "oracle", "postgresql"], "language": ["python", "java", "go"]} |
+-----------------------------------------------------------------------------------------------------------------------+
4 rows in set (0.00 sec)

替换操作,也就是修改update操作,使用的是 json_replace 函数
json_replace:只替换已经存在的旧值,不存在则忽略;

MySQL [test]> update employee set  skill_info = json_replace(skill_info, "$.language", "go") where empno = 3;
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0

MySQL [test]> select * from employee where empno = 3;
+-------+-----------------------------------------------------+------------------------------------------------------------+
| empno | basic_info                                          | skill_info                                                 |
+-------+-----------------------------------------------------+------------------------------------------------------------+
|     3 | {"age": 24, "from": "shanghai", "name": "zhaoqing"} | {"system": "linux", "database": "mysql", "language": "go"} |
+-------+-----------------------------------------------------+------------------------------------------------------------+
1 row in set (0.00 sec)

json_set:替换旧值,并插入不存在的新值;

MySQL [test]> update employee set  basic_info = json_set(basic_info, "$.age", 28,"$.sex" ,"man") where empno = 3;
Query OK, 1 row affected (0.01 sec)
Rows matched: 1  Changed: 1  Warnings: 0

MySQL [test]> 
MySQL [test]> select * from employee where empno = 3;
+-------+-------------------------------------------------------------------+------------------------------------------------------------+
| empno | basic_info                                                        | skill_info                                                 |
+-------+-------------------------------------------------------------------+------------------------------------------------------------+
|     3 | {"age": 28, "sex": "man", "from": "shanghai", "name": "zhaoqing"} | {"system": "linux", "database": "mysql", "language": "go"} |
+-------+-------------------------------------------------------------------+------------------------------------------------------------+
1 row in set (0.00 sec)

json_insert:插入新值,但不替换已经存在的旧值;

MySQL [test]> update  employee  set  basic_info = json_insert (basic_info, "$.age", 30, "$.phone" ,"123456789") where empno = 3;
Query OK, 1 row affected (0.01 sec)
Rows matched: 1  Changed: 1  Warnings: 0

MySQL [test]> select * from employee where empno = 3;
+-------+-----------------------------------------------------------------------------------------+------------------------------------------------------------+
| empno | basic_info                                                                              | skill_info                                                 |
+-------+-----------------------------------------------------------------------------------------+------------------------------------------------------------+
|     3 | {"age": 28, "sex": "man", "from": "shanghai", "name": "zhaoqing", "phone": "123456789"} | {"system": "linux", "database": "mysql", "language": "go"} |
+-------+-----------------------------------------------------------------------------------------+------------------------------------------------------------+
1 row in set (0.00 sec)

json_remove() 删除元素函数。

MySQL [test]> update  employee  set  basic_info = json_remove (basic_info, "$.sex", "$.phone") where empno = 3;
Query OK, 1 row affected (0.01 sec)
Rows matched: 1  Changed: 1  Warnings: 0

MySQL [test]> 
MySQL [test]> select * from employee where empno = 3;
+-------+-----------------------------------------------------+------------------------------------------------------------+
| empno | basic_info                                          | skill_info                                                 |
+-------+-----------------------------------------------------+------------------------------------------------------------+
|     3 | {"age": 28, "from": "shanghai", "name": "zhaoqing"} | {"system": "linux", "database": "mysql", "language": "go"} |
+-------+-----------------------------------------------------+------------------------------------------------------------+
1 row in set (0.00 sec)

结语

JSON数据类型是一个对开发十分友好的功能,有了它,MySQL的功能才更趋于完善。

 

attachments-2020-04-R7vKOf905e8aca9f0502c.jpg

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

(0)
上一篇 2023-02-14
下一篇 2023-02-14

相关推荐

  • Python Tkinter自定义滑块组件实现

    Python Tkinter自定义滑块组件实现Python Tkinter是Python标准库中一个GUI工具包,它提供了开发应用程序所需的各种GUI组件、窗口、框架等,灵活性强且易于使用。

    2024-04-05
    63
  • 袋鼠云 数据可视化_袋鼠云享

    袋鼠云 数据可视化_袋鼠云享最近,我们袋鼠云的UED部⻔小伙伴们,不声不响地⼲了⼀件⼤事——升级了全新设计语言「数栈UI5.0」。 众所周知,用户在使用产品时,是一个动态的过程,用户和产品之间进行交互的可用性,能否让用户愉悦、快

    2023-06-15
    164
  • Python代码获取UTC-4时区当前时间

    Python代码获取UTC-4时区当前时间时区是世界时间在地球上的区域上按照一定的规则划分成的标准时间。由于地球自转的角度是360度,一天的时间是固定的24小时,但因为地球的不同位置,同一时间,不同地方看到的太阳时角角度是不一样的。

    2024-01-07
    120
  • PostgreSQL 在视频、图片去重,图像搜索业务中的应用

    PostgreSQL 在视频、图片去重,图像搜索业务中的应用图像处理的业务场景比较多,例如 图像搜索、视频去重、人脸识别、美图、图片去重 等。

    比如,视频去重,一些用户上传了较多的视频,同一部电影可能有不同的版本,分辨率不一样,音轨不一样,压缩比不一样。这种

    2023-06-11
    156
  • MySQL版本引起的错误

    MySQL版本引起的错误各位看官可以关注博主个人博客,了解更多信息。 作者:Surpasser 链接地址:https://surpass.org.cn 前言 接上一篇帖子,博主在CentOS上安装了最新版的MySQL容器(版

    2023-04-15
    148
  • Python中的元组索引方法

    Python中的元组索引方法元组是Python中常见的一种数据结构,类似于列表,不同之处在于元组是不可变的,即其元素的值不可被修改。元组是用圆括号“()”进行定义的。例如:

    2024-01-21
    108
  • mysql笔记-

    mysql笔记-用单表接近一千万数据(四列:int,两个varchar,日期时间)测,发现几个效率几乎一致 count(0)=count(1)=count(数字)=count(*)>count(primary

    2023-02-15
    143
  • 企业级云数据库最佳实践[通俗易懂]

    企业级云数据库最佳实践[通俗易懂]云数据库 PostgreSQL 是京东智联云基于开源的 PostgreSQL构建的一款功能强大的企业级关系型数据库管理系统。加州大学计算机系开发的PostgreSQL,有“世界上可获得的最先进的开源…

    2023-02-25
    146

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注