官方文档
json 适用于text json等格式
- 判断是否json格式 json_valid(col)
- 转化为json格式 json_quote(col)
- 从json取值 json_extract(col,’ . k e y ′ ) 或 者 c o l − > ′ .key') 或者 col->' .key′)或者col−>′.key’
例子
一张需要审核的表
CREATE TABLE `json_test` (
`id` int NOT NULL AUTO_INCREMENT,
`sort` int NOT NULL DEFAULT '0',
`content` text,
`review` tinyint(1) DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB CHARSET=utf8;
插入数据
其中sort代表排序,content里面代表要更细的排序,review 1代表审核通过
要求如下:
1.如果审核通过,查询sort值
2.如果审核未通过,查询content里面sort的值
3.最终展示列表都是最新的。
4.部分content里面的格式有问题
处理思路:
* 使用json_valid判断,如果content符合json格式的话直接用,否则使用json_quote转化一下,确保都能使用正常json格式
* where 条件里面使用判断语句
* 查询sort或者content.sort为5的数据
select j.*,jt.content_json from json_test j
inner join
(select id, case when json_valid(content) then content else json_quote(content) end as content_json from json_test)jt
on j.id=jt.id
where
case when review=1 then sort=5
else content_json->'$.sort'=5 end
结果: