MySql5.7 json查询
create table t1(name json);
insert into t1 values('{
"hello": "song",
"num": 111,
"obj": { "who": "me", "arr": [ 1, 2, "three" ], "more": "hey" },
"bool": true,
"can": false,
"learning": null,
"chiness": "中文"
}' );
#返回json文本的深度
mysql> select json_depth(name) from t1;
输出结果----4;
1 rows in set (0.02 sec)
#返回json文本的长度
mysql> select json_length(name) from t1;
输出结果----9
1 rows in set (0.01 sec)
#返回json值得类型
mysql> select json_type(name) from t1;
输出结果----OBJECT
1 rows in set (0.04 sec)
#判读是否是合法的json类型
mysql> SELECT JSON_VALID('hello') a, JSON_VALID('"hello"') b;
返回结果:a:0 b:1
1 row in set (0.00 sec)
#查看存储的json有哪些key
mysql> select json_keys(name) as a from t1;
返回结果:array[
'a'=> ["hello", "link", "can", "num", "bool", "learning", "notLink", "obj", "chiness"],
]
1 rows in set (0.05 sec)
#查看name 字段的对象 obj有哪些key
mysql> select json_keys(name,'$.obj') as a from t1;
返回结果:a ["more","who","arr"]
5rowsinset(0.00sec)
#查看第一次出现的位置
mysql>select json_search(name,'one','me') as a from t1;
返回结果:"$.obj.who"
#查看所有包含aaaaa的位置
mysql> select json_search(name,'all','%aaaaa%') as a from t1;
返回结果:aaaaa所在的key json_search(name,’all’,’%json%’)
1rows in set (0.00 sec)
#抽取值 查找的key所对应的value json字符串中key为link的第0个值
mysql> select json_extract(name,'$.link[0]') as a from t1;
返回结果: null 数据中没后key为link,结果返回null
1 rows in set (0.00 sec)
mysql> select json_extract(name,'$.obj[0].more[0]') from t1;
返回结果:"hey"
1 rows in set (0.00 sec)
或者使用下面的方式
mysql> select name,name->'$.obj[0].more[0]' from t1;
返回结果:"hey"
1 rows in set (0.00 sec)
mysql> select JSON_ARRAY_APPEND(name,'$.name','xxx') from t1;
追加记录 在指定的json字段追加key-value 参数(字段名,key,value)
mysql> select JSON_REMOVE(name,'$.name') from t1;
删除json数据 参数(字段名,key)
mysql> select JSON_set(name,'$.name','ooo') from t1;
有就替换,没有就insert
mysql> SELECT JSON_UNQUOTE(JSON_EXTRACT(name, '$.name')) AS name from t1;
查询结果去掉双引号 返回字段name中的key为name的集合,没有“”
因为 JSON 不同于字符串,所以如果用字符串和 JSON 字段比较,是不会相等的可以通过
where key->'$.value'的形式去查询 ->和->>结果等效