mysql - 在 MYSQL 中的 JSON 字段中搜索值
问题描述
我试图了解“新”MYSQL JSON 字段。
我有这张桌子:
id (int-11, not_null, auto_inc)
customer_id (int-11, not null)
labels (json)
有了这些数据:
id: 1
customer_id: 1
labels: [{"isnew": "no", "tagname": "FOO", "category": "CAT_1", "isdeleted": "no"}, {"isnew": "yes", "tagname": "BAR", "category": "CAT_2", "isdeleted": "no"}]
JSON美化
[
{
"tagname": "FOO",
"category": "CAT_1",
"isnew": "no",
"isdeleted": "no"
},
{
"tagname": "BAR",
"category": "CAT_2",
"isnew": "yes",
"isdeleted": "no"
}
]
现在我想选择表中具有特定类别和特定标记名的所有客户(按 customer_id)
我试过这个:
SELECT * FROM labels_customers_json
WHERE JSON_SEARCH(labels, 'all', 'BAR') IS NOT NULL
但这不是我想要的。这个正在搜索每个 json 属性。我看过一些 JSON_EXTRACT 的例子:
SELECT * FROM `e_store`.`products`
WHERE
`category_id` = 1
AND JSON_EXTRACT(`attributes` , '$.ports.usb') > 0
AND JSON_EXTRACT(`attributes` , '$.ports.hdmi') > 0;
SELECT c, c->"$.id", g, n
FROM jemp
WHERE JSON_EXTRACT(c, "$.id") > 1
ORDER BY c->"$.name";
所以我尝试了这个
SELECT * FROM labels_customers_json
WHERE JSON_EXTRACT(labels, '$.tagname') = 'BAR'
SELECT labels, JSON_EXTRACT(labels, "$.customer_id"), customer_id
FROM labels_customers_json
WHERE JSON_EXTRACT(labels, "$.customer_id") > 0
解决方案
您可能可以尝试使用SELECT * FROM labels_customers_json WHERE JSON_SEARCH(labels, 'all', "BAR", NULL, "$[*].tagname") is not null
- 尽管我不能说这是否是执行此查询的最佳方式。
推荐阅读
- javascript - {{> afQuickField name='locationType' Optionvalue="locationType"}}
- r - 如何列出包中的所有 R Markdown 模板?
- matlab - 将字符串数组拆分为数字矩阵
- r - 可以将来自多个 .csv 文件(存储在同一文件夹中)的一列数据编译成一列吗?
- ios - iOS 15 SwiftUI 3 Picker 绑定在更改@State 值后不起作用
- sql - Oracle 发现按允许的插槽划分的间隙
- git - 在 git log --name-status 中,T 类型(“文件已更改”)是什么意思?
- flutter - 颤振 Navigator.of(context).restorablePushNamed 没有返回未来和任何结果
- c++ - C++17 std::variant 比动态多态性慢?
- python - 在我的简单 Python 代码中筛选出预测