1. 程式人生 > >MySQL JSON 型別資料操作

MySQL JSON 型別資料操作

1、Java 中動態擴充套件欄位,會導致資料庫表被鎖,在MySQL 5.7.8版本之前,因為MySQL不能直接操作JSON型別資料,可以將一個欄位設定成varchar型別,裡面存放JSON格式資料,這樣在需要擴充套件欄位時,不需要修改表結構;
2、mysql自5.7.8版本開始,就支援了json結構的資料儲存和查詢,這表明了mysql也在不斷的學習和增加nosql資料庫的優點。但mysql畢竟是關係型資料庫,在處理json這種非結構化的資料時,還是比較彆扭的。

建立JSON

類似 varchar,設定 JSON 主要將欄位的 type 是 json, 不能設定長度,可以是 NULL 但不能有預設值

CREATE TABLE muscleape
(
  id       TINYINT UNSIGNED NOT NULL AUTO_INCREMENT,
  category JSON,
  tags     JSON,
  PRIMARY KEY (id)
);
DESC muscleape;
Field type Null Key Default Extra
id tinyint(3) unsigned NO PRI auto_increment
category json YES "" ""
tags json YES "" ""

插如JSON資料

1、插入 json 格式的字串,可以是物件的形式,也可以是陣列的形式;
2、可以使用JSON_OBJECT、JSON_ARRAY函式生成;(其他JSON函式:https://dev.mysql.com/doc/refman/5.7/en/json-creation-functions.html

-- 直接插入字串
INSERT INTO muscleape (category, tags) VALUES ('{"id": 1,"name": "muscleape"}','[1,2,3]');
-- 使用JSON函式
INSERT INTO muscleape (category, tags) VALUES (JSON_OBJECT("id",2,"name","muscleape_q"),JSON_ARRAY(1,3,5));
-- 

新增的資料如下:

SELECT * FROM muscleape;
id category tags
1 {"id": 1, "name": "muscleape"} [1, 2, 3]
2 {"id": 2, "name": "muscleape_q"} [1, 3, 5]

查詢JSON

1、查詢JSON中的資料用 column->path的形式,其中物件型別path的表示方式 $.path,陣列型別的表示方式 $[index];

SELECT id,category->'$.id',category->'$.name',tags->'$[0]',tags->'$[2]' FROM muscleape;
id category->'\(.id' | category->'\).name' tags->'\([0]' | tags->'\)[2]'
1 1 "muscleape" 1 3
2 2 "muscleape_q" 1 5

2、查詢結果中字串型別還包含有雙引號,可以使用JSON_UNQUOTE函式將雙引號去掉,從MySQL 5.7.13開始也可以使用操作符 ->>

SELECT id,category->'$.name',JSON_UNQUOTE(category->'$.name'),category->>'$.name',tags->'$[0]',tags->'$[2]' FROM muscleape;
id category->'\(.name' | JSON_UNQUOTE(category->'\).name') category->>'$.name'
1 "muscleape" muscleape muscleape
2 "muscleape_q" muscleape_q muscleape_q

JSON 作為條件搜尋

1、JSON不同於字串,如果直接和JSON欄位比較,不會查詢到結果:

-- 查詢不到資料
SELECT * FROM muscleape WHERE category = '{"id": 1,"name": "muscleape"}';
-- 查詢不到資料

2、使用CAST將字串轉成JSON的形式:

SELECT * FROM muscleape WHERE category = CAST('{"id": 1,"name": "muscleape"}' AS JSON);
id category tags
1 {"id": 1, "name": "muscleape"} [1, 2, 3]

3、上面提到column->path形式從select中查詢出的字串包含雙引號,這裡作為查詢條件是沒有影響的,->和->>的結果是一樣的;

-- 以下的查詢結果相同
SELECT * FROM muscleape WHERE category->'$.name' = 'muscleape';
SELECT * FROM muscleape WHERE category->>'$.name' = 'muscleape';

4、注意(MySQL:5.7.17):JSON中的元素搜尋是嚴格區分變數型別的,比如整型和字串時嚴格區分的(->的形式),但是:->>型別是不區分的:

-- 能查到
SELECT * FROM muscleape WHERE category->'$.id' = 1;
-- 不能
SELECT * FROM muscleape WHERE category->'$.id' = '1';
-- 能查到
SELECT * FROM muscleape WHERE category->>'$.id' = 1;
-- 能查到
SELECT * FROM muscleape WHERE category->>'$.id' = '1';

5、可以使用JSON_CONTAINS函式,但是該函式的第二個引數不接受整型,無論JSON元素時整型還是字串(第二個引數只能是數字,不能用字元)

SELECT * FROM muscleape WHERE JSON_CONTAINS(category,1,'$.id');
-- 上面SQL執行報錯,報錯資訊:ERROR 3146 (22001): Invalid data type for JSON data in argument 2 to function json_contains; a JSON string or JSON type is required.
SELECT * FROM muscleape WHERE JSON_CONTAINS(category,'1','$.id');
-- 可以查詢到資料

6、對於陣列型別的JSON查詢,比如tags中包含有2個數據,同樣要用JSON_CONTAINS函式,同樣第二個引數也需要是字串

SELECT * FROM muscleape WHERE JSON_CONTAINS(tags,'1');

更新JSON

函式:http://dev.mysql.com/doc/refman/5.7/en/json-modification-functions.html

1、更新整個JSON,與插入時類似

UPDATE muscleape SET tags = '[1, 3, 4]' WHERE id = 1;

2、JSON_INSERT()函式

插入新值,但不會覆蓋已存在的值

UPDATE muscleape SET category = JSON_INSERT(category,'$.name','muscleape_new','$.url','muscleape.com') WHERE id = 1;
-- name沒有被修改,url的值已經新增進去了

3、JSON_SET()函式

插入新值,並覆蓋已存在的值

UPDATE muscleape SET category = JSON_SET(category,'$.host','localhost','$.url','www.muscleape.com') WHERE id = 1;

4、JSON_REPLACE()函式
只替換已存在的值

UPDATE muscleape SET category = JSON_REPLACE(category,'$.host','127.0.0.1','$.address','shandong') WHERE id = 1;

5、JSON_REMOVE()函式
刪除JSON元素

UPDATE muscleape SET category = JSON_REMOVE(category,'$.host','$.url') WHERE id = 1;
UPDATE muscleape SET tags = JSON_REMOVE(tags,'$[0]') WHERE id = 1;

6、JSON_ARRAY_APPEND()陣列中增加元素

UPDATE muscleape SET tags = JSON_ARRAY_APPEND(tags,'$[0]',4) WHERE id = 1;
id category tags
1 {"id": 1, "name": "muscleape"} [[1, 4], 2, 3]

7、JSON_ARRAY_INSERT()陣列中新增元素

UPDATE muscleape SET tags = JSON_ARRAY_INSERT(tags,'$[0]',5) WHERE id = 1;
id category tags
1 {"id": 1, "name": "muscleape"} [5, [1, 4], 2, 3]

建立索引

MySQL的JSON格式資料不能直接建立索引,但是可以變通一下,把要搜尋的資料單獨拎出來,單獨一個數據列,然後在這個欄位上建立一個索引,官方的例子:

CREATE TABLE muscleape_office(
  c JSON,
  g INT GENERATED ALWAYS AS (c->"$.id"),
  INDEX i (g)
);
DESC muscleape_office;
Field type Null Key Default Extra
c json YES "" ""
g int(11) YES MUL VIRTUAL GENERATED
INSERT INTO muscleape_office (c)
VALUES
  ('{"id": "1", "name": "Fred"}'),
  ('{"id": "2", "name": "Wilma"}'),
  ('{"id": "3", "name": "Barney"}'),
  ('{"id": "4", "name": "Betty"}');
SELECT c->>'$.name' AS name FROM muscleape_office WHERE g > 2;
name
Barney
Betty
EXPLAIN SELECT c->>'$.name' AS name FROM muscleape_office WHERE g > 2;
id select_type table partitions type posible_keys key key_len ref rows filtered Extra
1 SIMPLE muscleape_office range i i 5 2 100 Using where