问题描述
我想从 JSON 文件中搜索产品 ID,但我无法从 JSON 文件中搜索。在 JSON 字段中添加多级值,如下图所示。
SELECT equip_id FROM ' . $table. ' where JSON_CONTAINS(category,["1"])
我想通过 productID 搜索产品,请告诉我如何实现这一点。
下面是我的桌子的完整图片
解决方法
我创建了一个用于测试的表:
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 |
+-------------------+
,
我用以下数据创建了一个临时表。
当我使用以下查询进行上述集合时的输出
select * from table_name where json_contains(product,'{"productID" : "1"}')