首页 > 解决方案 > 在 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

标签: mysql

解决方案


您可能可以尝试使用SELECT * FROM labels_customers_json WHERE JSON_SEARCH(labels, 'all', "BAR", NULL, "$[*].tagname") is not null- 尽管我不能说这是否是执行此查询的最佳方式。


推荐阅读