代码改变世界

MySQL的Json类型个人用法详解

2023-09-04 16:05  北桥苏  阅读(94)  评论(0编辑  收藏  举报

 前言

虽然MySQL很早就添加了Json类型,但是在业务开发过程中还是很少设计带这种类型的表。少不代表没有,当真正要对Json类型进行特定查询,修改,插入和优化等操作时,却感觉一下子想不起那些函数怎么使用。比如把json里的某个键和值作为SQL条件,修改某个键下的子键的值,其中可能会遇到数组形式的Json或者键名是字符串的数字修改异常等问题。那么,以下是小北在业务中常遇到的Json类型操作汇总了。

 

查询

1. 查询普通键

以下示例是从goods表的price字段里取出price键的值,可以依次往下取值,就是price.嵌套键名即可。

select json_extract(price, "$.price") as de from goods where id = 159540

2. 查询字符串类型的数字键

虽然以上能解决大部分取值,但有时候的json嵌套里有字符串类型的数字键名,如下图的json,要取出字段下sku键名的 "45453"键algorithm的值。

select json_extract(price, "$.sku.\"45453\".algorithm") as de from price where id = 159540

3. 查询数组类的Json指定值

以上的两种是我们常见的对象类,但当出现数组类时,就没有键名了,取值只需要指定索引即可,如下分别是查询某值和根据json的某值作为查询条件。

select JSON_EXTRACT(`crumbs`, $[1]) as one_crumbs from comment where id = 4565
select * from comment where JSON_EXTRACT(`crumbs` ,'$[1]') = 256

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)