在MYSQL的JSON字段中搜索值

时间:2018-07-27 10:17:40

标签: mysql

我正在尝试了解“新的” 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

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

您也可以使用JSON_SEARCH搜索特定路径。因此,您可以使用以下查询:

SELECT * 
FROM labels_customers_json 
WHERE JSON_SEARCH(labels, 'all', 'BAR', NULL, '$[*].tagname') IS NOT NULL

您还可以同时使用JSON_EXTRACTJSON_CONTAINS

SELECT *
FROM labels_customers_json
WHERE JSON_CONTAINS(JSON_EXTRACT(labels, '$[*].tagname'), '["BAR"]') > 0;

您也只能使用JSON_CONTAINS进行检查:

SELECT *
FROM labels_customers_json
WHERE JSON_CONTAINS(labels, '{"tagname":"BAR"}') > 0;
  

演示: https://www.db-fiddle.com/f/rufrThAQPfXHrK9YyibFSm/2