MySQL根据属性值返回JSON数组索引 [英] MySQL Return JSON array index based on property value
问题描述
我有一个包含JSON数据的表,如下所示:
I have a table with JSON data like this:
{"a": [{"color": "blue", "value": 15}, {"color": "red", "value": 30}]}
我需要获取位于"blue"同一对象内的"value".
I need to get the "value" that is inside the same object of "blue".
我想使用下面的代码:
SELECT JSON_EXTRACT(my_data, '$.a[0].value');
问题在于蓝色"对象可以位于数组的任何索引中.
The problem is that the "blue" object can be in any index of the array.
那么,有没有一种方法可以先检索索引,然后再使用正确的索引进行查询?
So, is there a way to retrieve the index first and then i'll query using the right index?
更新
Barmar的答案有效,但需要包装在JSON_UNQUOTE()
The Barmar's answer works but it needs to wrap in JSON_UNQUOTE()
推荐答案
使用JSON_SEARCH()
查找blue
的路径.
SELECT JSON_EXTRACT(my_data, REPLACE(JSON_SEARCH(my_data, 'one', 'blue'), '.color', '.value'))
JSON_SEARCH
将返回类似于$.a[0].color
的字符串. REPLACE
将其更改为$.a[0].value
,然后提取该元素.
JSON_SEARCH
will return a string like $.a[0].color
. REPLACE
changes that to $.a[0].value
, then you extract that element.
这篇关于MySQL根据属性值返回JSON数组索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!