mysql系列之json类型操作

一、简介

        本篇文章将会介绍mysql json数据类型的相关操作。

二、json类型 操作指南

2.1 指定字段类型为json

CREATE TABLE `student` (
  `id` int NOT NULL AUTO_INCREMENT,
  `info` json DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

INSERT INTO student.student( info) VALUES('{"age": 26, "username": "admin"}');
2.2 ->  / JSON_EXTRACT

       -> 可以用于查询json的某个内容

SELECT info->'$.username' as username FROM student.student;
SELECT  JSON_EXTRACT(info, '$.username','$.age')  FROM student.student  ;
2.3 JSON_CONTAINS

      json contains 用于查询是否有对应value

SELECT  * FROM student.student where JSON_CONTAINS(info, '{"username":"admin"}') ;
2.4 JSON_CONTAINS_PATH

        JSON_CONTAINS_PATH 用于检查指定的key是否存在

SELECT  * FROM student.student where JSON_CONTAINS_PATH(info, 'one','$.age') ;
2.5 JSON_INSERT / JSON_REPLACE / JSON_REMOVE

       JSON_REPLACE 用于替换指定字段内容

update student.student set info = JSON_REPLACE(info, '$.username','vicyor') where JSON_CONTAINS(info, '{"username":"admin"}')  ;

       JSON_INSERT 用户插入新字段

update student.student set info = JSON_INSERT(info, '$.gender','man') where id =1 ;

      JSON_REMOVE 移除指定字段

update student.student set info = JSON_REMOVE (info, '$.gender') where id =1 ;

你可能感兴趣的:(json)