mysqljson字段长度_mysql5.7新增的json字段类型
⼀、我们先创建⼀个表,准备点数据
CREATE TABLE `json_test` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID',
`json` json DEFAULT NULL COMMENT 'json数据',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
⼆、检索json列的字段
通过使⽤ -> 或 ->> 运算符检索json列的字段
select id, json->'$[0].items[0].name' from json_test;
select id, json->'$[0].items[0].name' from json_test;
使⽤ -> 和 ->> 的区别是结果⽤了引号包裹。
三、处理json的⼀些函数
JSON_PRETTY(json_val) 以优雅的格式显⽰json值
json值的类型有哪些select id, JSON_PRETTY(json) from json_test\G;
JSON_CONTAINS(target, candidate[, path]) 判断给定的candidate是否包含在target中,如果指定了path,则在指定路径中进⾏查。
注意,注意,注意,这⾥的candidate如果是数字,需要⽤单引号包裹,如果是字符串,单引号⾥再加上双引号包裹。
select JSON_CONTAINS(json->'$[0].name', '"1号篮⼦"') from json_test;
select JSON_CONTAINS(json, '"1号篮⼦"', '$[0].name') from json_test;
JSON_CONTAINS_PATH(json_doc, one_or_all, path[, path] ...) 判断json_doc中的路径是否存在,通俗点说就是json中的key是否存在
select JSON_CONTAINS_PATH(json, 'one', '$[0].name', '$[0].test') from json_test;
第⼆个参数'one'表⽰只要有⼀个key存在就返回1,否则为0
select JSON_CONTAINS_PATH(json, 'all', '$[0].name', '$[0].test') from json_test;
第⼆个参数'all'表⽰所有key存在才返回1,否则为0
JSON_SET(json_doc, path, val[, path, val] ...) 插⼊或更新数据并返回结果
select JSON_SET(json, '$[0].name', '2号篮⼦', '$[0].test', 'test') from json_test;
我们修改$[0].name的值,并添加⼀个key为test,值为test的项
JSON_INSERT(json_doc, path, val[, path, val] ...) 插⼊数据并返回结果,但不替换现有值。
select JSON_INSERT(json, '$[0].name', '2号篮⼦', '$[0].exts', '扩展') from json_test;
这时$[0].name不会被更新,只会新增⼀个字段$[0].exts
JSON_REPLACE(json_doc, path, val[, path, val] ...) 替换现有值并返回结果
select JSON_REPLACE(json, '$[0].name', '替换') from json_test;
将$[0].name中的值替换成新值
JSON_REMOVE(json_doc, path[, path] ...) 删除数据并返回结果
select JSON_REMOVE(json, '$[0].name') from json_test;
删除$[0].name这项数据
JSON_KEYS(json_doc[, path]) 获取json⽂档中的所有键
select JSON_KEYS(json, '$[0]') from json_test;
获取$[0]路径下的所有键
JSON_LENGTH(json_doc[, path]) 获取json⽂档的长度
select JSON_LENGTH(json, '$[0]') from json_test;
获取$[0]下的元素数量
JSON_EXTRACT(json_doc, path[, path] ...) 返回json⽂档中的数据
select JSON_EXTRACT(json, '$[0]') from json_test;
select JSON_EXTRACT(json, '$[0].name') from json_test;
返回json⽂档指定路径下的数据
JSON_ARRAY([val[, val] ...]) 创建json数组
select JSON_ARRAY(1, '2', true, 5.6, null, now());
JSON_OBJECT([key, val[, key, val] ...]) 通过键值对, 创建json对象
select JSON_OBJECT('name', 'xiaoxu', 'age', 28, 'height', 1.72);
注意,这⾥键和值要成对出现
JSON_MERGE_PATCH(json_doc, json_doc[, json_doc] ...) 合并json⽂档,如果有重复键,后⾯的数据覆盖前⾯的
select JSON_MERGE_PATCH('{"name":"test1"}', '{"name":"test2"}');
JSON_MERGE_PRESERVE(json_doc, json_doc[, json_doc] ...) 合并json⽂档,如果有重复键,则会通过数组把值都保存起来select JSON_MERGE_PRESERVE('{"name":"test1"}', '{"name":"test2"}');
JSON_QUOTE(string) 通过⽤双引号字符包裹并转义内部引号和其他字符
select JSON_QUOTE('你好"世界"');
JSON_UNQUOTE(json_val) 将转义字符转换回普通字符
select JSON_UNQUOTE('你好\\t\"世界\"');
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论