如何提取存儲在字段中的值爲json。在客戶目前存儲在juniferResponse領域如{「客戶ID」:1}Mysql如何提取存儲的JSON值
後續沒有在MySQL的版本工作,我現在用:
SELECT json_extract(juniferResponse, '$.customerId') AS cid FROM enrolment WHERE juniferResponse IS_NOT_NULL;
我需要從中提取價值juniferResponse字段不爲空或空的地方。
如何提取存儲在字段中的值爲json。在客戶目前存儲在juniferResponse領域如{「客戶ID」:1}Mysql如何提取存儲的JSON值
後續沒有在MySQL的版本工作,我現在用:
SELECT json_extract(juniferResponse, '$.customerId') AS cid FROM enrolment WHERE juniferResponse IS_NOT_NULL;
我需要從中提取價值juniferResponse字段不爲空或空的地方。
如果你不能upgrate MySQL來5.7.8或海格。 它可以使用下面的選擇:如果在客戶鍵不存在
13 is the number of letters in the locate string ["customerId":]
或創建功能類似下面
SET @a='{"z":"\\"customerId\\"","customerId":41,"a":1,"b2":2}';
SELECT IF(LOCATE('"customerId":',@a)>0,1*substring(@a,LOCATE('"customerId":',@a)+13),NULL);
的選擇返回null。這是比較有用的即時
DELIMITER //
CREATE FUNCTION json_extract_int (jstring TEXT,jkey CHAR(20))
RETURNS INT(11)
BEGIN
SET jkey = CONCAT('"',jkey,'":');
RETURN IF(LOCATE(jkey,jstring)>0,1*substring(jstring,LOCATE(jkey,jstring)+LENGTH(jkey)),NULL);
END//
DELIMITER ;
很容易使用
SELECT json_extract_int(@a,'customerId');
+-----------------------------------+
| json_extract_int(@a,'customerId') |
+-----------------------------------+
| 41 |
+-----------------------------------+
或在您的情況
SELECT json_extract_int(juniferResponse,'customerId');
如果您無法升級您的mysql服務器以使用json_extract,並且您不能在應用程序中使用json_decode,則可以使用MID和LOCATE。 但是你的JSON將不得不像像{「some_key」:some_number} 你可以使用下面的查詢:
SELECT
MID(
juniferResponse,
LOCATE(':', juniferResponse) + 1,
LOCATE('}', juniferResponse) - LOCATE(':', juniferResponse) - 1
) AS cid
FROM `exam`
WHERE juniferResponse IS NOT NULL
是'juniferResponse'爲JSON字符串? – codtex
我認爲我沒有得到你的任務,因爲我看着這段代碼,你會做類似於'SELECT 1 AS cid FROM enrollment WHERE juniferResponse IS_NOT_NULL;'這對我沒有意義...' – codtex
如果你不喜歡不需要執行聚合,或者結果的條件,你可以在PHP中提取json json_decode($ row ['juniferResponse'],true)//將提取爲數組 –