1.目的
mysql的列是固定的,不支持存儲如Map 結構的數據,但現在我們的需求是希望有一個 ext Map的擴展列,可以存儲Map結構的數據,并且可以在mysql里面進行運算.(即schema free)。所以解決方案是創建一個map_get()函數,可以根據key得到對應的value
函數功能:
/*
* 用于解析map結構的數據,根據傳入的inputKey返回相對應的value
* * @params
* map: 自定義鍵值對的Map數據格式,輸入例子: username:badqiu,age:25,sex:F
* key: 輸入key
* @return 返回key對應的value,如果沒有值,則返回null */
map_get(map varchar2,key varchar2)
2.實現
set global log_bin_trust_function_creators = 1;
/*
map_get(map,inputKey)函數
用于解析map結構的數據,根據傳入的inputKey返回相對應的value
*/
DROP FUNCTION IF EXISTS map_get;
DELIMITER $$ -- 定義函數分隔符,必須要有,可以不是$$
CREATE FUNCTION map_get( map varchar(5000), inputKey varchar(300) )
RETURNS VARCHAR(255) BEGIN
DECLARE rowSeperator char(1) default ','; -- 行分隔符
DECLARE fieldSeperator char(1) default ':'; -- 鍵值對分隔符
DECLARE tempMap varchar(255) default map;
DECLARE isEnd boolean default false;
DECLARE rowIndex int default 0;
DECLARE pair varchar(255);
DECLARE pairIndex varchar(255);
DECLARE strKey varchar(255);
DECLARE strValue varchar(255);
WHILE isEnd = false do
set rowIndex = locate(rowSeperator,tempMap);
if rowIndex > 0 then
set pair = substring(tempMap,1,rowIndex-1);
set tempMap = substring(tempMap,rowIndex+1,9999999);
else
set pair = tempMap;
set isEnd = true;
end if;
set pairIndex = locate(fieldSeperator,pair);
if pairIndex > 0 then
set strKey = substring(pair,1,pairIndex-1);
set strValue = substring(pair,pairIndex+1,9999999);
if inputKey = strKey then
return strValue;
end if;
end if;
END WHILE;
return null; END $$
DELIMITER; DROP FUNCTION IF EXISTS map_get_number;
DELIMITER $$ -- 定義函數分隔符,必須要有,可以不是$$
CREATE FUNCTION map_get_number( map varchar(5000), inputKey varchar(300) )
RETURNS DECIMAL
BEGIN
return cast(map_get(map,inputKey) AS DECIMAL );
END $$
DELIMITER;
3.測試
select map_get('username:badqiu','username')
union all
select map_get('username:badqiu,age:100','not exist')
union all
select map_get_number('username:badqiu,age:200','age')
union all
select map_get_number('username:badqiu,age:200','agexxxxx')
union all
select map_get('username:badqiu,age:100','age');