mysql從5.7開始才支持JSON_EXTRACT等 JSON相關的函數,mysql
項目裏用到的mysql是5.6的,須要提取JSON字段裏某一個屬性值進行統計,sql
本身寫了一個笨的提取方法: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返回。ci
裏面用到了幾個mysql自帶函數字符串
1. position 定位字符串 子串的位置it
2. substr 字符串截取io
3. convert 數據類型轉換數據類型