2017-03-08 451 views
0

如何提取存储在字段中的值为json。在客户目前存储在juniferResponse领域如{“客户ID”:1}Mysql如何提取存储的JSON值

后续没有在MySQL的版本工作,我现在用:

SELECT json_extract(juniferResponse, '$.customerId') AS cid FROM enrolment WHERE juniferResponse IS_NOT_NULL; 

我需要从中提取价值juniferResponse字段不为空或空的地方。

+0

是'juniferResponse'为JSON字符串? – codtex

+0

我认为我没有得到你的任务,因为我看着这段代码,你会做类似于'SELECT 1 AS cid FROM enrollment WHERE juniferResponse IS_NOT_NULL;'这对我没有意义...' – codtex

+0

如果你不喜欢不需要执行聚合,或者结果的条件,你可以在PHP中提取json json_decode($ row ['juniferResponse'],true)//将提取为数组 –

回答

0

如果你不能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'); 
-1

如果您无法升级您的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