说明:json除了键值对的形式以外,还包括Array数列形式,这在mysql5.7及以上也是支持的,对Array中元素的操作相当于直接对键值对中的值操作,少了“键”的定位这一步,这里不单独展示,所有的函数都都同时支持,大同小异
1. insert(插入)操作
先用insert给出操作面向的数据对象
insert into jwc(st_num,info) value('131141','{"数学":[95,4],"英语":{"英语上":[87,3],"英语下":[82,3]},"体育":"不及格"}')
2. select(投影)操作
对于JSON数据的选择有一个重要的函数——json_extract()
//选择“数学”对应的值
select json_extract(info,"$.数学") from jwc where id='131141'
也可以用info->”$.数学”代替json_extract()函数
//选择“数学”对应的值
select info->"$.数学" from jwc where id='131141'
用json_keys()函数选择所有的键值
select json_keys(info) from jwc
json中的path路径
.a.b:表示键a下的键b.a.b:表示键a下的键b.a[1]:表示键a对应的值(如果是列表的话)的第二个元素
3. where选择操作
json_contains(column,elem,key)函数判断包含带有elem元素的key的column属性是否存在
//注意中间elem(95)一定要用字符串形式表示
select * from jwc where json_contains(info,'95','$.数学')
json_search()函数:直接对“值”(且值必须是字符串,数列或者键值对都不行)或数列中的元素操作
//json_search的第二个参数one表示找一个,all表示找到所有
select * from jwc where json_search(info,'one',"%及格") is not null;
直接利用键值进行选择
select * from jwc where info->'$.数学[0]'>90;
4. update更新操作
json_array_append()函数:直接在定位元素的后面添加
//对于非列表的值直接扩展成列表
update personal_info set info=json_array_append(info,'$."数学"',4) where id=6;
json_array_insert()函数:在指定位置插入元素
update personal_info set info=json_array_insert(info,'$."数学"[0]',4) where id=6;
json_set():直接设定某值
update personal_info set info=json_set(info,'$."数学"',4) where id=6;
json_merge(column,key-value)函数:向json类型字段中添加元素
update personal_info set info=json_merge(info,'{"提示":"this is a test"}') where id=6;
json_replace()函数
update personal_info set info=json_replace(info,'$."提示"','this is another test') where id=6;
缺陷与思考
上述 是关于mysql对json数据类型的操作介绍,下面分析一下json数据类型使用的一些问题。
所有的函数在选择时候的依据都是“值”,不能依靠“键”,如json_search,json_contain,这样对于键的选择就必须要指明,这在一些结构不固定,“键”不明确的情况不太方便。
没有发现对“键”的模糊查找
很多情况下,对值的修改都限定为字符串,不能改为数列或者键值对形式。如下将数学的值直接改为数列是不能执行的:
update personal_info set info=json_replace(info,'$."提示"','this is another test','$."数学"',[94,3]) where id=6;
也就说,对数列和字典的支持还不够。
以上提出的这些缺陷或许是因为我对mysql了解不够深入,或许mysql有相应的解决办法,这里暂时存疑,希望知道的朋友能告知,以上。