前言
尽管MySQL很早就增加了Json类型,然而在业务开发过程中还是很少设计带这种类型的表。少不代表没有,当真正要对Json类型进行特定查问,批改,插入和优化等操作时,却感觉一下子想不起那些函数怎么应用。比方把json里的某个键和值作为SQL条件,批改某个键下的子键的值,其中可能会遇到数组模式的Json或者键名是字符串的数字批改异样等问题。那么,以下是小北在业务中常遇到的Json类型操作汇总了。
查问
1. 查问一般键
以下示例是从goods表的price字段里取出price键的值,能够顺次往下取值,就是price.嵌套键名即可。
select json_extract(price, "$.price") as de from goods where id = 1595402.
2. 查问字符串类型的数字键
尽管以上能解决大部分取值,但有时候的json嵌套里有字符串类型的数字键名,如下图的json,要取出字段下sku键名的 “45453”键algorithm的值。
select json_extract(price, "$.sku.\"45453\".algorithm") as de from price where id = 1595403.
3. 查问数组类的Json指定值
以上的两种是咱们常见的对象类,但当呈现数组类时,就没有键名了,取值只须要指定索引即可,如下别离是查问某值和依据json的某值作为查问条件。
select JSON_EXTRACT(`crumbs`, $[1]) as one_crumbs from comment where id = 4565select * from comment where JSON_EXTRACT(`crumbs` ,'$[1]') = 2564.
4. 查问Json里是否蕴含某个值
select * from goods_item where goods_id=10263 and JSON_CONTAINS(item_value->'$', concat(43318,''));
select * from goods_item where goods_id=10263 and JSON_CONTAINS(item_value, concat(43318,''));
select * from goods_item where goods_id=10263 and JSON_CONTAINS(item_value, concat(43318,''),'$');
5. 查问Json长度
以下的goods_img是一个数组类的Json字段,通过长度作为SQL的查问条件。
select id, stock_no, goods_img from goods_item where state = 1 and JSON_LENGTH(goods_img) < 3
更新
1. 批改Json字段下指定键的值
update price set price = json_set(price, "$.attr.\"1280\".price_old", 300) where id in (171314)