mysql - 如何在 Mysql 8 中的 JSON 内的嵌套数组中搜索值?
问题描述
假设我有一个具有以下结构的 JSON 对象:
{
"_id":"0000abcdefg",
"type":"PP",
"subscription":{
"subscribers":{
"physicSubscribers":[
{
"civility":"M",
"lastname":"DOE",
"firstname":"John",
"emailAddress":"john-doe@something.com",
},
{
"civility":"M",
"lastname":"smith",
"firstname":"TED",
"emailAddress":"ted-smith@something.com",
}
]
}
}
}
如何通过 subscription.subscribers.physicSubscribers[*].firsname 搜索文档,但在比较之前将值转换为小写?
我已经尝试了一些解决方案,但它总是返回一个空结果:
SELECT doc ->> '$'
FROM customers
WHERE lower(JSON_EXTRACT(doc,'$.subscription.subscribers.physicSubscribers[*].firstname')) = 'john'
谢谢!
解决方案
在 WHERE 中使用 JSON_EXTRACT() 看起来不正确 - 它返回一个您尝试与单个值进行比较的数组。所以你必须另外在这个数组中搜索。
你可以使用 JSON_SEARCH,并指定正确的排序规则:
SELECT doc ->> '$'
FROM customers
WHERE JSON_SEARCH(doc,
'one',
'john' COLLATE utf8mb4_0900_ai_ci,
NULL,
'$.subscription.subscribers.physicSubscribers[*].firstname') IS NOT NULL
https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=12d9f1c860d5433e26bbf9279c92f09c
推荐阅读
- python-3.x - 本地 spark 连接到远程 hive 和 hadoop
- mysql - 是否可以在 mysql 中将 2 行合并为 1 行?
- xamarin.forms - Xamarin.Froms MVVMCross 加载模式视图
- maven - 为什么我会得到“线程“主”java.lang.NoClassDefFoundError:org/openqa/selenium/WebDriver 中的异常”?
- ios - 如何无限期地重试 URL 请求,直到使用 Alamofire 5 成功?
- python - 如何在使用熊猫数据框创建的箱形图上添加特定点?
- javascript - javascript onscroll动画不起作用
- python - 在 Django 中更新用户模型详细信息后无法登录
- c# - 从一个类访问另一个类的变量
- java - Struts 应用中的问题