簡體   English   中英

MySQL如何提取存儲的JSON值

[英]Mysql how to extract stored JSON value

如何提取以json格式存儲在字段中的值。 customerId當前存儲在juniferResponse字段中,例如{“ customerId”:1}

以下不適用於我正在使用的mysql版本:

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

我需要從juniferResponse提取值,其中該字段不為null或為空。

如果您不能將MySQL升級到5.7.8或更高版本。 可以使用以下選擇:

SET @a='{"z":"\\"customerId\\"","customerId":41,"a":1,"b2":2}';

SELECT IF(LOCATE('"customerId":',@a)>0,1*substring(@a,LOCATE('"customerId":',@a)+13),NULL);

如果customerId鍵不存在,則選擇返回NULL

13 is the number of letters in the locate string ["customerId":]

或創建如下函數。 哪個更有用

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM