在MYSQL中的JSON字段中搜索值

在MYSQL中的JSON字段中搜索值,mysql,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", "ca

我试图理解“新”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"}]
使用此数据:

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"
  }
]
现在,我想选择表中具有特定类别和特定标记名的所有客户(按客户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\u customers\u json,其中json\u SEARCH(labels,'all','BAR',NULL,$[*].tagname)不是空的
——尽管我不能说这是否是执行此查询的最佳方式。

您也可以使用它在特定路径上进行搜索。因此,您可以使用以下查询:

SELECT * 
FROM labels_customers_json 
WHERE JSON_SEARCH(labels, 'all', 'BAR', NULL, '$[*].tagname') IS NOT NULL
您还可以将和一起使用:

SELECT *
FROM labels_customers_json
WHERE JSON_CONTAINS(JSON_EXTRACT(labels, '$[*].tagname'), '["BAR"]') > 0;
您还可以使用仅用于检查:

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


你使用什么版本的mysql?刚刚安装了最新的wamp版本:mysqlnd 5.0.11-devThen任何人都有此方面的经验?它现在有正确的版本,5.7.22。我的phpmyadmin已经过时了,它是4.8.2,但是仍然有这样的问题?从标签\u客户\u json中选择*,其中json提取中的“测试”(标签,$[*].tagname)。它在“JSON_EXTRACT”附近返回一个语法错误……它可以工作,但你们的答案是一样的。我不知道谁是第一个给我复述的人。根据时间戳,我的是4秒前的,但塞巴斯蒂安更详细。编辑作品,但你们的答案是一样的。我不知道谁是第一个给出这个描述的。@JordiHuertas有一个特定的类别和一个特定的标记名-在同一个对象上,或者可以是不同的对象?它可以有不同的属性。这是一个标签系统,用于标记客户。因此,标记名可以在许多客户中具有不同的类别。例如,它应该可以让我找到一个客户,该客户的标签来自“email”或“posal_mail”类别中的“unsubscribed”。我正在将JSON保存在文本字段中,但现在使用PHP处理所有JSON太复杂了。