5

我在 mysql5.7 上使用 JSON 对象类型。如果我有一个具有一层的 json 对象,我工作得很好,但是如果我有一个内部有一组对象的对象,我在查询数组中的值时遇到问题。

这是我的表:

id (int) | json_data (JSON)
-----------------------------------------------------------------
   1     | {'name':'joe', 'array':[{'prop':first','value':'1'},
         |    {'prop':second','value':'2'}]}
   2     | {'name':'bob', 'array':[{'prop':third','value':'3'}]}

我正在尝试编写一个查询,该查询将检索数组中包含 value=1 的对象的所有记录。

我试过这个查询:

SELECT * from myTable where json_data->'$.array[0].value' = '1'; 

它有效,但只是因为我正在专门检查数组中的第一个值。如何检查数组的所有元素?

我尝试使用json_data->'$.array[*].value', json_data->'$.array[.].value', json_data->'$.array[?].value',它们都不起作用。

搜索数组的所有元素的方法是什么?

4

1 回答 1

1

您可以使用JSON_SEARCH函数。此函数返回 json 对象中给定字符串的路径,但您也可以使用它来检索结果,因为如果元素不存在则返回 null

在您的情况下,运行:

select JSON_SEARCH(json_data, 'all', '1', null, '$.array[*].value') from myTable

将返回'$.array[0].value'第一行和null第二行。

所以用它来做:

select * from myTable where JSON_SEARCH(json_data, 'all', '1', 
null, '$.array[*].value') is not null

只获取第一行。

于 2016-01-01T20:45:14.793 回答