📅  最后修改于: 2023-12-03 15:17:45.919000             🧑  作者: Mango
MySQL 从 5.7.8 版本开始支持 JSON 数据类型,这使得 MySQL 可以存储和查询 JSON 数据。在进行 JSON 数据查询时,Mysql 为我们提供了一些函数,如 JSON_CONTAINS、JSON_EXTRACT 等。而对于 JSON 对象数组的查询,我们可以使用 JSON_SEARCH 函数。本文将介绍如何使用 MySQL 的 JSON_SEARCH 函数搜索 JSON 对象数组。
JSON_SEARCH 函数用于返回匹配指定键/值对的 JSON 数组元素的路径。语法如下:
JSON_SEARCH(json_doc, one_or_all, search_str[, escape_char[, path] ...])
其中:
假设我们有以下 JSON 对象数组数据:
{
"books": [
{
"title": "JavaScript: The Good Parts",
"author": "Douglas Crockford",
"year": 2008
},
{
"title": "Effective JavaScript: 68 Specific Ways to Harness the Power of JavaScript",
"author": "David Herman",
"year": 2012
},
{
"title": "JavaScript: The Definitive Guide: Activate Your Web Pages",
"author": "David Flanagan",
"year": 2011
}
]
}
我们可以使用以下语句查询包含 "JavaScript: The Definitive Guide" 的元素所在路径:
SELECT JSON_SEARCH('{"books":[{"title":"JavaScript: The Good Parts","author":"Douglas Crockford","year":2008},{"title":"Effective JavaScript: 68 Specific Ways to Harness the Power of JavaScript","author":"David Herman","year":2012},{"title":"JavaScript: The Definitive Guide: Activate Your Web Pages","author":"David Flanagan","year":2011}]}' , 'one', 'JavaScript: The Definitive Guide')
输出结果为:
$."books"[2]."title"
这个结果告诉我们,要查询的元素位于 JSON 路径 $."books"[2]."title"。
Mysql 具有强大的 JSON 查询功能,而 JSON_SEARCH 函数为我们查询 JSON 对象数组提供了很多便利。但是需要注意,当 JSON 数组中包含重复元素时,JSON_SEARCH 只会返回第一个查找到的元素所在路径,并不会返回所有的匹配路径。