我如何使用 json_extract() 查询 SQL 中嵌套的 JSON 数据值?

How would I query nested JSON data values in SQL using json_extract()?

Mysql版本为6.7+

我需要从下方获取值的列示例。

json_extract(goal_templates.template_data, group_concat('$.resources')) ->这导致所有行的 NULL return。

:template_data
{"Resolve housing issues": {"tasks": [{"name": "Use Decision Map to explore paths to resolving'' housing issue", "end_date": "15 days", "taskType": 3, "help_text": "", "resources": [], "start_date": "today", "actionOrder": "1", "recur_every": "", "resource_reference_id": ""}, {"name": "Select a local Debt & Credit Counseling Service", "end_date": "15 days", "taskType": 3, "help_text": "Add & tag local Credit & Debt Counseling Service (Organization)", "resources": ["14579", "14580"], "start_date": "today", "actionOrder": "2", "recur_every": "", "resource_reference_id": "14579, 14580"}, {"name": "[Schedule Credit & Debt Counseling as SGE or RGE]", "end_date": "15 days", "taskType": 3, "help_text": "", "resources": [], "start_date": "today", "actionOrder": "3", "recur_every": "", "resource_reference_id": ""}, {"name": "Rate resource for benefit of those who follow", "end_date": "15 days", "taskType": 3, "help_text": "", "resources": [], "start_date": "today", "actionOrder": "4", "recur_every": "", "resource_reference_id": ""}], "sequence_num": "1"}}
mysql> select json_extract(template_data, '$."Resolve housing issues".tasks[*].resources') as resources from goal_templates;
+----------------------------------+
| resources                        |
+----------------------------------+
| [[], ["14579", "14580"], [], []] |
+----------------------------------+

我们使用 JSON_EXTRACTJSON_COLUMN 中提取密钥,语法如下:

JSON_EXTRACT(json_field, '$.key')

但是,如果我们需要像您的情况一样提取嵌套键,我们可以将嵌套的子键附加到路径中,例如

JSON_EXTRACT('{"resolve_housing_issues": {"tasks": [{"name": "Decision Map", "end_date": "15 days"}]}}', '$.resolve_housing_issues.tasks[0].name') 

如@bill-karwin 的回答中所述,或使用如下通配符:

SELECT JSON_EXTRACT('{"resolve_housing_issues": {"tasks": [{"name": "Decision Map", "end_date": "15 days"}]}}', '$**.resolve_housing_issues') as resolve_housing_issues;

它产生以下结果:

查询时

SELECT JSON_EXTRACT('{"resolve_housing_issues": {"tasks": [{"name": "Decision Map", "end_date": "15 days"}]}}', '$**.tasks') as tasks;
产生以下结果:

依此类推。

有关此内容的更多信息,请参见 here

我要找的选择器似乎是“$**”通配符。这使我能够获取每一行的所有未命名对象和嵌套资源的值。

JSON_EXTRACT(template_data, '$**.tasks[*].resources') AS resources