【问题标题】:How to fetch specific values from json in MySQL如何从 MySQL 中的 json 中获取特定值
【发布时间】:2020-05-08 16:09:35
【问题描述】:

我有一个表,MySQL 版本 = 5.7

表_1

ID        Json
IR-1      {Json}
IR-2      {Json}

示例 Json 字符串

{
  "flag": false,
  "resp": "RTUI",
  "mean": "r-2",
  "details": {
    "product": "IR JAD",
    "status": "failed",
    "datetime": "26/09/2017"
  }
}

我想获取字段respmeanstatus,格式如下。我正在使用下面提到的查询,但它只能以 ["failed"] 格式获取status

select ID,
json_extract(Json, '$.*.resp') AS resp,
json_extract(Json, '$.*.mean') AS mean,
json_extract(Json, '$.*.status') AS status
from Table_1
where ID in ('IR-1','IR-2');

需要的输出:

ID     resp     mean      status
IR-1   RTUI     r-2       failed

【问题讨论】:

    标签: mysql


    【解决方案1】:

    您不应该将.* 用于顶级属性。

    另外,明确指定details 属性可能比使用wildcard 访问嵌套的status 属性更好。

    select ID,
        json_extract(Json, '$.resp') AS resp,
        json_extract(Json, '$.mean') AS mean,
        json_extract(Json, '$.details.status') AS status
    from Table_1
    where ID in ('IR-1','IR-2');
    

    DEMO

    【讨论】:

    • 现在我得到了“r-2”格式的mean,但respstatus仍然没有出现。
    • 我的演示使用 MySQL 5.7。
    • 非常感谢,它成功了。有没有办法去掉双引号?
    • 使用JSON_UNQUOTE()
    猜你喜欢
    • 2017-09-19
    • 1970-01-01
    • 2019-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多