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

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