1. 程式人生 > 實用技巧 >json資料的增刪改查

json資料的增刪改查

建立一個表class

DROP TABLE IF EXISTS `class`;

CREATE TABLE `class` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(20) NOT NULL COMMENT '使用者名稱',
`desc` json NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic COMMENT '班級表';

1插入:

1.1 insert into class(`id` ,`name`,`desc`) values (1 ,'jimao','{"sex":"1","high":"183","work":"programmer"}')

1.2可以使用JSON_OBJECT()函式構造json物件

INSERT INTO class(`name`,`desc`) VALUES('liming', JSON_OBJECT("sex", 0, "age", 17));

1.3使用JSON_ARRAY()函式構造json陣列

INSERT INTO class(`name`,`desc`) VALUES('guozihao', JSON_OBJECT("sex", 1, "age", 25, "tag", JSON_ARRAY(3,5,90)));

2查詢

2.1查詢所有資料

select *from class

2.2查詢json中的單個值

這是發現desc是關鍵字,所以重新刪掉建新表

DROP TABLE IF EXISTS `class`;

CREATE TABLE `class` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(20) NOT NULL COMMENT '使用者名稱',
`detail` json NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic COMMENT '班級表';

insert into class(`id` ,`name`,`detail`) values (1 ,'jimao','{"sex":"1","high":"183","work":"programmer"}');

INSERT INTO class(`name`,`detail`) VALUES('liming', JSON_OBJECT("sex", 0, "age", 17));

INSERT INTO class(`name`,`detail`) VALUES('guozihao', JSON_OBJECT("sex", 1, "age", 25, "tag", JSON_ARRAY(3,5,90)));

SELECT * FROM class

SELECT JSON_EXTRACT(detail, '$.age'), JSON_EXTRACT(detail, '$.sex'), JSON_EXTRACT(detail, '$.tag[0]')from class

等同於select name, detail->'$.age', detail->'$.sex', detail->'$.tag[0]' from class;

2.3查詢結果去掉雙引號

可以用JSON_UNQUOTE函式將雙引號去掉

select name, JSON_UNQUOTE(detail->'$.sex') from class

或者用->>來取引號中的值

select name, detail->>'$.sex' from class ;

按照json中欄位的屬性關聯查詢,注意sex的值帶引號和不帶引號是兩種值

可以對儀表新增虛擬列

ALTER TABLE `class` ADD `sex` VARCHAR(50) GENERATED ALWAYS AS (detail->>'$.sex') VIRTUAL

然後用select name,sex FROM class where sex='1';查詢出對應的結果

3更新

3.1JSON_INSERT()插入新值,但是不會覆蓋已經存在的值

更新前的頁面

更新後的頁面

更新語句

UPDATE class SET detail = JSON_INSERT(detail,'$.age',35, '$.sex','1','$.high', '179','$.money','1800') where id=1;

3.2JSON_SET()插入新值,並覆蓋已經存在的值

更新前的表

更新後的表

更新語句

UPDATE class SET detail = JSON_SET(detail,'$.sex','2','$.paymoney2', '900') where id=2;

3.3JSON_REPLACE:只替換存在的值

更改前

更改後

sql:UPDATE class SET detail = JSON_REPLACE(detail, '$.sex', 9, '$.tag', '[1,2,3]') where id=3;

4刪除

移除json中的某個元素

刪除前的表

刪除後的表

sql:

UPDATE class SET detail = JSON_REMOVE(detail, '$.paymoney', '$.paymoney2') where id=2;