在 mysql 5.7

问题描述

我想从 JSON 文件搜索产品 ID,但我无法从 JSON 文件搜索。在 JSON 字段中添加多级值,如下图所示。

enter image description here

我可以从其他文件搜索数据,例如

SELECT equip_id FROM ' . $table. ' where  JSON_CONTAINS(category,["1"])

enter image description here

我想通过 productID 搜索产品,请告诉我如何实现这一点。

下面是我的桌子的完整图片

enter image description here

解决方法

我创建了一个用于测试的表:

mysql> select * from mytable;
+----------------------------------------------------------------------+------------+
| product                                                              | category   |
+----------------------------------------------------------------------+------------+
| [{"OrderId": 1,"productID": "1"}]                                   | ["2","3"] |
| [{"OrderId": 2,"3"] |
| [{"OrderId": 3,"3"] |
| [{"OrderId": 4,"3"] |
| [{"OrderId": 5,"3"] |
| [{"OrderId": 6,"productID": "1"},{"OrderID": 7,"productID": "2"}] | ["2","3"] |
+----------------------------------------------------------------------+------------+

现在我想检查是否有任何产品有 productID 2 的订单?

mysql> select json_contains(json_extract(product,'$[*].productID'),'["2"]') as `product_2_present` from mytable;
+-------------------+
| product_2_present |
+-------------------+
|                 0 |
|                 0 |
|                 0 |
|                 0 |
|                 0 |
|                 1 |
+-------------------+
,

我用以下数据创建了一个临时表。

enter image description here

当我使用以下查询进行上述集合时的输出

select * from table_name where json_contains(product,'{"productID" : "1"}')

enter image description here