Mysql JSON字段提取某一个属性值的函数

mysql从5.7开始才支持JSON_EXTRACT等 JSON相关的函数,

项目里用到的mysql是5.6的,需要提取JSON字段里某一个属性值进行统计,

自己写了一个笨的提取方法:

CREATE DEFINER=`root`@`%` FUNCTION `jsonExtract`(`fieldName` varchar(30),`jsonStr` varchar(1024)) RETURNS double
  BEGIN
    declare firstPos int;
    declare firstStr varchar(1024);
    declare secondPos int;
    declare thirdPos int;
    declare resultStr varchar(200);
    declare result double;
    set firstPos = POSITION(fieldName IN jsonStr);
    set firstStr = SUBSTR(jsonStr,firstPos);
    set secondPos = POSITION(':' IN firstStr);
    set thirdPos = POSITION(',' IN firstStr);
    set resultStr = SUBSTR(firstStr,secondPos+1,thirdPos-secondPos-1);
    set result = CONVERT(resultStr,decimal(20,6));
    RETURN result;
  END

我这里最后转成了double返回。

里面用到了几个mysql自带函数

1. position 定位字符串 子串的位置

2. substr  字符串截取

3. convert 数据类型转换

猜你喜欢

转载自www.cnblogs.com/selfchange/p/10256472.html