gpt4 book ai didi

mysql - 在 MYSQL 中搜索 JSON 字段中的值

转载 作者:行者123 更新时间:2023-11-29 05:04:21 25 4
gpt4 key购买 nike

我正在尝试理解“新的”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 - 虽然我不能说这是否是执行此查询的最佳方式。

关于mysql - 在 MYSQL 中搜索 JSON 字段中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51555847/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com