关于后端:MySQL的Json类型个人用法详解

3次阅读

共计 1229 个字符,预计需要花费 4 分钟才能阅读完成。

前言

尽管 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)

正文完
 0