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的值帶引號和不帶引號是兩種值

 select name, detail->>'$.age' from class where detail->'$.age'=28

 

 

 

 

 

可以對儀表新增虛擬列

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;

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM