【问题标题】:Mysql how to extract stored JSON valueMysql如何提取存储的JSON值
【发布时间】:2017-07-29 01:08:52
【问题描述】:

如何将存储在字段中的值提取为 json。 customerId 当前存储在 juniferResponse 字段中,例如 {"customerId":1}

以下在我使用的mysql版本中不起作用:

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

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

【问题讨论】:

  • juniferResponse 作为 json 字符串?
  • 我想我没有得到你的要求,因为我看这段代码你会做类似SELECT 1 AS cid FROM enrolment WHERE juniferResponse IS_NOT_NULL; 这对我来说没有意义的事情......
  • 如果你不需要执行聚合,或者结果的条件,你可以在 PHP 中提取 json json_decode($row['juniferResponse'], true) // 将提取作为数组
  • juniferResponse 是列的名称,它有一个像 {"customerId":1} 这样的存储值我需要获取 1,它是列不为空的 id。
  • @DanIonescu 我宁愿在查询中这样做,因为我必须更新一个大型数据库。

标签: php mysql json


【解决方案1】:

如果您无法将 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');

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-08
      • 1970-01-01
      • 2018-03-26
      • 1970-01-01
      • 2023-03-30
      • 2016-03-13
      • 2018-05-05
      • 1970-01-01
      相关资源
      最近更新 更多