如何从mysql中嵌套的json字段中检索特定字段?

问题描述 投票:0回答:1

我的数据表中有以下列(描述字段),我必须在其中提取国家/地区名称字段值。就像这个领域的

Spain

[
  {
    "key": "country_code",
    "type": "string",
    "value": "12"
  },
  {
    "key": "country_name",
    "type": "string",
    "value": "Spain"
  },
  {
    "key": "timezone",
    "type": "string",
    "value": "Europe/Madrid"
  },
  {
    "key": "latitude",
    "type": "string",
    "value": "40.37603"
  },
  {
    "key": "longitude",
    "type": "string",
    "value": "-3.69901"
  }
]

enter image description here

如何提取?请帮帮我。

SELECT
  json_extract(description, '$.key[1]') AS country
FROM
  test_table;
mysql json nested
1个回答
0
投票

你是这个意思吗

SET @j = '[
  {
    "key": "country_code",
    "type": "string",
    "value": "12"
  },
  {
    "key": "country_name",
    "type": "string",
    "value": "Spain"
  },
  {
    "key": "timezone",
    "type": "string",
    "value": "Europe/Madrid"
  },
  {
    "key": "latitude",
    "type": "string",
    "value": "40.37603"
  },
  {
    "key": "longitude",
    "type": "string",
    "value": "-3.69901"
  }
]';

SELECT JSON_EXTRACT(json_elem, '$.value') AS country_name_value
FROM JSON_TABLE(@j, '$[*]' COLUMNS (
  json_elem JSON PATH '$'
) ) AS jt
WHERE JSON_EXTRACT(json_elem, '$.key') = 'country_name';

示例在这里:https://dbfiddle.uk/AgVBNJSd

© www.soinside.com 2019 - 2024. All rights reserved.