mysql支持原生json使用說明

正文

MySQL在5.7.8開始對json原生支持,本文將對MySQL中json類型的用法簡單說明,但願對你有用。php

CREATE TABLE testproject (

   `id` int(10) unsigned NOT NULL AUTO_INCREMENT,

   `skill` JSON NOT NULL,

   `student` JSON NOT NULL,

   PRIMARY KEY (`id`)

);複製代碼

查看錶結構:html

在這裏插入圖片描述

這樣JSON的字段就被建立好了前端

注:JSON類型不能有默認值。vue

插入JSON

插入 json 格式的字符串,能夠是對象的形式,也能夠是數組的形式,java

INSERT INTO `testproject` (student, skill) VALUES ('{"id": 1, "name": "ggjg"}', '["java", "go", "vue"]');
INSERT INTO `testproject` (student, skill) VALUES ('{"id": 5, "name": "guogege"}', '[]');複製代碼

插入json時,數據庫會對json作校驗,不符合json規範就會報錯。python

在這裏插入圖片描述

查詢JSON:

查詢 json 中的數據用 column->path 的形式,其中對象類型 path 這樣表示 $.path, 而數組類型則是 $[index]mysql

查詢testproject表student字段中json對象id爲1的記錄:面試

SELECT * FROM testproject WHERE student->'$.id'= 1;複製代碼

在這裏插入圖片描述

查詢testproject表student字段中json對象id爲1或者5的記錄:spring

SELECT * FROM testproject WHERE student->'$.id' in (1,5);

SELECT * FROM testproject WHERE student->'$.id' = 1 or student->'$.id' = 5;複製代碼

在這裏插入圖片描述

也能夠用函數json_extract:sql

在這裏插入圖片描述

column->path方法有限制,數據源必須是表字段,不然就報錯:在這裏插入圖片描述

如下這樣查詢,查出來student->'$.name'包含雙引號:

SELECT id, student->'$.id', student->'$.name', skill->'$[0]', skill->'$[2]' FROM testproject;複製代碼

在這裏插入圖片描述

這不是咱們想要的,能夠用 JSONUNQUOTE 函數將雙引號去掉,從 MySQL 5.7.13 起也能夠經過這個操做符 ->> 這個和 JSONUNQUOTE 是等價的。

在這裏插入圖片描述

由於 JSON 不一樣於字符串,因此若是用字符串和 JSON 字段比較,是不會相等的:

mysql> SELECT * FROM testproject WHERE student = '{"id": 1, "name": "ggjg"}';
Empty set (0.00 sec)複製代碼

此時能夠經過 CAST 將字符串轉成 JSON 的形式:

mysql>  SELECT * FROM testproject WHERE student = CAST('{"id": 1, "name": "ggjg"}' as JSON);
+----+-----------------------+---------------------------+
| id | skill                 | student                   |
+----+-----------------------+---------------------------+
| 10 | ["java", "go", "vue"] | {"id": 1, "name": "ggjg"} |
+----+-----------------------+---------------------------+
1 row in set (0.01 sec)複製代碼

要特別注意的是,JSON 中的元素搜索是嚴格區分變量類型的,好比說整型和字符串是嚴格區分的:

mysql> SELECT * FROM testproject WHERE student->'$.id' = '1';
Empty set (0.00 sec)

mysql>
mysql> SELECT * FROM testproject WHERE student->'$.id' = 1;
+----+-----------------------+---------------------------+
| id | skill                 | student                   |
+----+-----------------------+---------------------------+
| 10 | ["java", "go", "vue"] | {"id": 1, "name": "ggjg"} |
+----+-----------------------+---------------------------+
1 row in set (0.00 sec)複製代碼

能夠看到搜索字符串 1 和整型 1 的結果是不同的。

除了用以上 column->path 的形式搜索,還能夠用JSONCONTAINS 函數,但和 column->path 的形式有點相反的是,JSONCONTAINS 第二個參數是不接受整數的,不管 json 元素是整型仍是字符串,不然會出現這個錯誤:

mysql> SELECT * FROM testproject WHERE JSON_CONTAINS(student, 1, '$.id');
ERROR 3146 (22032): Invalid data type for JSON data in argument 2 to function json_contains; a JSON string or JSON type is required.
mysql>複製代碼

這裏必需要使用字符串:

mysql> SELECT * FROM testproject WHERE JSON_CONTAINS(student, '1', '$.id');
+----+-----------------------+---------------------------+
| id | skill                 | student                   |
+----+-----------------------+---------------------------+
| 10 | ["java", "go", "vue"] | {"id": 1, "name": "ggjg"} |
+----+-----------------------+---------------------------+
1 row in set (0.00 sec)複製代碼

對於數組類型的 JSON 的查詢,好比說 skill 中包含有 3 的數據,一樣要用 JSON_CONTAINS 函數,一樣第二個參數也須要是字符串:

mysql> SELECT * FROM testproject WHERE JSON_CONTAINS(skill, '"go"');
+----+-----------------------+---------------------------+
| id | skill                 | student                   |
+----+-----------------------+---------------------------+
| 10 | ["java", "go", "vue"] | {"id": 1, "name": "ggjg"} |
+----+-----------------------+---------------------------+
1 row in set (0.00 sec)

mysql> SELECT * FROM testproject WHERE JSON_CONTAINS(skill, '1');
+----+-----------+------------------------------+
| id | skill     | student                      |
+----+-----------+------------------------------+
| 12 | [1, 2, 3] | {"id": 4, "name": "guogege"} |
+----+-----------+------------------------------+
1 row in set (0.00 sec)複製代碼

更新數據

MySQL 並不支持 column->path 的形式進行更新操做。

若是是整個 json 更新的話,和插入時相似的:

mysql> select * from testproject where id = 10;                          
+----+-----------------------+---------------------------+               
| id | skill                 | student                   |               
+----+-----------------------+---------------------------+               
| 10 | ["java", "go", "vue"] | {"id": 1, "name": "ggjg"} |               
+----+-----------------------+---------------------------+               
1 row in set (0.00 sec)                                                  
                                                                        
mysql> UPDATE testproject SET skill = '["js", "java"]' WHERE id = 10;    
Query OK, 1 row affected (0.01 sec)                                      
Rows matched: 1  Changed: 1  Warnings: 0                                 
                                                                        
mysql> select * from testproject where id = 10;                          
+----+----------------+---------------------------+                      
| id | skill          | student                   |                      
+----+----------------+---------------------------+                      
| 10 | ["js", "java"] | {"id": 1, "name": "ggjg"} |                      
+----+----------------+---------------------------+                      
1 row in set (0.00 sec)複製代碼

jsonarrayappend和jsonarrayinsert函數使用:

jsonarrayappend是在json後面追加;

jsonarrayinsert是在指定下標插入。

mysql> select * from testproject;                                            
+----+----------------+------------------------------+                       
| id | skill          | student                      |                       
+----+----------------+------------------------------+                       
| 10 | ["js", "java"] | {"id": 1, "name": "ggjg"}    |                       
| 11 | []             | {"id": 5, "name": "guogege"} |                       
| 12 | [1, 2, 3]      | {"id": 4, "name": "guogege"} |                       
+----+----------------+------------------------------+                       
3 rows in set (0.00 sec)                                                     
                                                                            
mysql> SELECT json_array_append(skill, '$', 'c') from testproject;           
+------------------------------------+                                       
| json_array_append(skill, '$', 'c') |                                       
+------------------------------------+                                       
| ["js", "java", "c"]                |                                       
| ["c"]                              |                                       
| [1, 2, 3, "c"]                     |                                       
+------------------------------------+                                       
3 rows in set (0.00 sec)                                                     
                                                                            
mysql> SELECT json_array_insert(skill, '$[1]', 'php') from testproject;      
+-----------------------------------------+                                  
| json_array_insert(skill, '$[1]', 'php') |                                  
+-----------------------------------------+                                  
| ["js", "php", "java"]                   |                                  
| ["php"]                                 |                                  
| [1, "php", 2, 3]                        |                                  
+-----------------------------------------+                                  
3 rows in set (0.00 sec)                                                     
                                                                            
mysql>複製代碼

jsonreplace、jsonset、jsoninsert和jsonremove函數用法:

json_replace:只替換已經存在的舊值,不存在則忽略;

json_set:替換舊值,並插入不存在的新值;

json_insert:插入新值,但不替換已經存在的舊值;

json_remove() 刪除元素。

json_replace:

mysql> select * from testproject;                                                                                      
+----+----------------+--------------------------------+                                                               
| id | skill          | student                        |                                                               
+----+----------------+--------------------------------+                                                               
| 10 | ["js", "java"] | {"id": 1, "name": "smallsoup"} |                                                               
| 11 | []             | {"id": 5, "name": "guogege"}   |                                                               
| 12 | [1, 2, 3]      | {"id": 4, "name": "guogege"}   |                                                               
+----+----------------+--------------------------------+                                                               
3 rows in set (0.00 sec)                                                                                               
                                                                                                                      
mysql>                                                                                                                 
mysql> UPDATE testproject SET student->'$.name' = 'smallsoup' where student->'$.id' = 1;                               
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server versio
n for the right syntax to use near '->'$.name' = 'smallsoup' where student->'$.id' = 1' at line 1                      
mysql>                                                                                                                 
mysql> UPDATE testproject SET student = json_replace(student, '$.name', 'soup') WHERE student->'$.id' = 1;             
Query OK, 1 row affected (0.01 sec)                                                                                    
Rows matched: 1  Changed: 1  Warnings: 0                                                                               
                                                                                                                      
mysql> select * from testproject;                                                                                      
+----+----------------+------------------------------+                                                                 
| id | skill          | student                      |                                                                 
+----+----------------+------------------------------+                                                                 
| 10 | ["js", "java"] | {"id": 1, "name": "soup"}    |                                                                 
| 11 | []         | {"id": 5, "name": "guogege"} |                                                                 
| 12 | [1, 2, 3]    | {"id": 4, "name": "guogege"} |                                                                 
+----+----------------+------------------------------+                                                                 
3 rows in set (0.00 sec)複製代碼

json_set:

mysql> select * from testproject;
+----+----------------+------------------------------+
| id | skill          | student                      |
+----+----------------+------------------------------+
| 10 | ["js", "java"] | {"id": 1, "name": "soup"}    |
| 11 | []             | {"id": 5, "name": "guogege"} |
| 12 | [1, 2, 3]      | {"id": 4, "name": "guogege"} |
+----+----------------+------------------------------+
3 rows in set (0.00 sec)

mysql>  UPDATE testproject SET student = json_set(student, '$.name', 'small', '$.age', 22) WHERE student->'$.id'= 1;
Query OK, 1 row affected (0.01 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> select * from testproject;
+----+----------------+---------------------------------------+
| id | skill          | student                               |
+----+----------------+---------------------------------------+
| 10 | ["js", "java"] | {"id": 1, "age": 22, "name": "small"} |
| 11 | []             | {"id": 5, "name": "guogege"}          |
| 12 | [1, 2, 3]      | {"id": 4, "name": "guogege"}          |
+----+----------------+---------------------------------------+
3 rows in set (0.00 sec)複製代碼

json_insert:

mysql> select * from testproject;                                                                                      
+----+----------------+---------------------------------------+                                                        
| id | skill          | student                               |                                                        
+----+----------------+---------------------------------------+                                                        
| 10 | ["js", "java"] | {"id": 1, "age": 22, "name": "small"} |                                                        
| 11 | []             | {"id": 5, "name": "guogege"}          |                                                        
| 12 | [1, 2, 3]      | {"id": 4, "name": "guogege"}          |                                                        
+----+----------------+---------------------------------------+                                                        
3 rows in set (0.00 sec)                                                                                               
                                                                                                                      
mysql> UPDATE testproject SET student = json_insert(student, '$.name', 'soup', '$.addr', '蘇州') WHERE student->'$.id'=  
1;                                                                                                                    
Query OK, 1 row affected (0.00 sec)                                                                                    
Rows matched: 1  Changed: 1  Warnings: 0                                                                               
                                                                                                                      
mysql> select * from testproject;                                                                                      
+----+----------------+---------------------------------------------------------+                                      
| id | skill          | student                                                 |                                      
+----+----------------+---------------------------------------------------------+                                      
| 10 | ["js", "java"] | {"id": 1, "age": 22, "addr": "蘇州", "name": "small"}   |                                        
| 11 | []             | {"id": 5, "name": "guogege"}                            |                                      
| 12 | [1, 2, 3]      | {"id": 4, "name": "guogege"}                            |                                      
+----+----------------+---------------------------------------------------------+                                      
3 rows in set (0.00 sec)複製代碼

json_remove() :

mysql> select * from testproject;
+----+----------------+---------------------------------------------------------+
| id | skill          | student                                                 |
+----+----------------+---------------------------------------------------------+
| 10 | ["js", "java"] | {"id": 1, "age": 22, "addr": "蘇州", "name": "small"}   |
| 11 | []             | {"id": 5, "name": "guogege"}                            |
| 12 | [1, 2, 3]      | {"id": 4, "name": "guogege"}                            |
+----+----------------+---------------------------------------------------------+
3 rows in set (0.00 sec)

mysql> UPDATE testproject SET student = json_remove(student, '$.name', '$.age') WHERE student->'$.id' = 1;
Query OK, 1 row affected (0.01 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> select * from testproject;
+----+----------------+------------------------------+
| id | skill          | student                      |
+----+----------------+------------------------------+
| 10 | ["js", "java"] | {"id": 1, "addr": "蘇州"}    |
| 11 | []             | {"id": 5, "name": "guogege"} |
| 12 | [1, 2, 3]      | {"id": 4, "name": "guogege"} |
+----+----------------+------------------------------+
3 rows in set (0.00 sec)複製代碼

能夠看到name和age就被移除了。

以上只列出了部分函數的說明,mysql官方提供的函數列表以下:

在這裏插入圖片描述

更多用法請查看官方文檔:

https://dev.mysql.com/doc/refman/5.7/en/json-function-reference.html

本公衆號免費提供csdn下載服務,海量IT學習資源,若是你準備入IT坑,勵志成爲優秀的程序猿,那麼這些資源很適合你,包括但不限於java、go、python、springcloud、elk、嵌入式 、大數據、面試資料、前端 等資源。同時咱們組建了一個技術交流羣,裏面有不少大佬,會不定時分享技術文章,若是你想來一塊兒學習提升,能夠公衆號後臺回覆【2】,免費邀請加技術交流羣互相學習提升,會不按期分享編程IT相關資源。

掃碼關注,精彩內容第一時間推給你

image

相關文章
相關標籤/搜索