简体   繁体   English

在MYSQL中的JSON字段中搜索值

[英]Search for a value in a JSON field in MYSQL

I am trying to understand the "new" MYSQL JSON field. 我试图理解“新”MYSQL JSON字段。

I have this table: 我有这张桌子:

id (int-11, not_null, auto_inc)
customer_id (int-11, not null)
labels (json)

With this data: 有了这些数据:

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 beautify JSON美化

[
  {
    "tagname": "FOO",
    "category": "CAT_1",
    "isnew": "no",
    "isdeleted": "no"
  },
  {
    "tagname": "BAR",
    "category": "CAT_2",
    "isnew": "yes",
    "isdeleted": "no"
  }
]

And now I want to SELECT all the customers (by customer_id) in the table that have a specific category and a specific tagname 现在我想要在表中选择具有特定类别和特定标记名的所有客户(通过customer_id)

I tried this one: 我试过这个:

SELECT * FROM labels_customers_json
WHERE JSON_SEARCH(labels, 'all', 'BAR') IS NOT NULL

But this is not what I want. 但这不是我想要的。 This one is searching in every json attribute. 这个是在每个json属性中搜索。 I have seen some examples of JSON_EXTRACT: 我见过一些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";

So I tried this 所以我尝试了这个

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 - 尽管我不能说这是否是执行此操作的最佳方式查询。

You can use JSON_SEARCH to search on a specific path too. 您也可以使用JSON_SEARCH搜索特定路径。 So you can use the following query: 所以你可以使用以下查询:

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

You can also use JSON_EXTRACT and JSON_CONTAINS together: 您还可以一起使用JSON_EXTRACTJSON_CONTAINS

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

You can also use only JSON_CONTAINS to check: 您也可以只使用JSON_CONTAINS来检查:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM