mysql5.7 JSON类型体验 原

前言:为了兼容传统的sql语句,mysql5.7支持原生的json格式的字符串,即将关系型数据库和文档型集于一身。

1.使用json类型需要先查看一下当前mysql的版本

select version();

2.创建json类型的字段,用mysql图形客户端的需要下载支持mysql5.7新特型的。

CREATE TABLE `test_table` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `content` json DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;

 

3.插入

INSERT into test_table VALUES(null,'{"name":"测试1","age":1}');
INSERT into test_table VALUES(null,'{"name":"测试2","age":10}');

 

4.提取json里面的参数

SELECT json_extract(content,'$.name') as name ,json_extract(content,'$.age') as age from test_table

 

5.更新json字段的参数

JSON_REPLACE()替换已有的,如果是新的参数,不会添加

update test_table set content=json_replace(content,'$.name',"测1") where json_extract(content,'$.age')=1

 

6.添加json字段的参数

JSON_INSERT()可以添加新值,但它不会替换已存在的值。

update test_table set content=json_insert(content,'$.sex',"男") where json_extract(content,'$.age')=1

 

7.更新或新增json字段的参数

JSON_SET()替换已有的参数,如果没有会新增。

update test_table set content=json_set(content,'$.sex1',"女") where json_extract(content,'$.age')=1

 

8.删除json字段的参数

JSON_REMOVE()移除JSON文档中给定的一个或多个参数,如果不存在的话,函数会忽略。

update test_table set content=json_remove(content,'$.sex1') where json_extract(content,'$.age')=1

 

博客地址:https://my.oschina.net/wangnian

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章