mysql5.7 json object - 查询数组元素
mysql5.7 json object - query elements of an array
我在 mysql5.7 上使用 JSON 对象类型。如果我有一个具有一层的 json 对象,我会工作得很好,但如果我有一个内部包含对象数组的对象,我在查询数组中的值时会遇到问题。
这是我的 Table:
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'
、 none 它们都有效。
搜索数组所有元素的方法是什么?
可以使用JSON_SEARCH功能。此函数 return 是 json 对象中给定字符串的路径,但您也可以使用它来检索结果,因为如果元素不存在,它 return 为 null
在你的情况下,运行:
select JSON_SEARCH(json_data, 'all', '1', null, '$.array[*].value') from myTable
第一行将 return '$.array[0].value'
,第二行将 null
。
所以用它来做:
select * from myTable where JSON_SEARCH(json_data, 'all', '1',
null, '$.array[*].value') is not null
只获取第一行。
我在 mysql5.7 上使用 JSON 对象类型。如果我有一个具有一层的 json 对象,我会工作得很好,但如果我有一个内部包含对象数组的对象,我在查询数组中的值时会遇到问题。
这是我的 Table:
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'
、 none 它们都有效。
搜索数组所有元素的方法是什么?
可以使用JSON_SEARCH功能。此函数 return 是 json 对象中给定字符串的路径,但您也可以使用它来检索结果,因为如果元素不存在,它 return 为 null
在你的情况下,运行:
select JSON_SEARCH(json_data, 'all', '1', null, '$.array[*].value') from myTable
第一行将 return '$.array[0].value'
,第二行将 null
。
所以用它来做:
select * from myTable where JSON_SEARCH(json_data, 'all', '1',
null, '$.array[*].value') is not null
只获取第一行。