在 mysql 中搜索 Json 5.7
Search in Json in mysql 5.7
我想从 JSON 字段中搜索产品 ID,但无法从 JSON 字段中搜索。在 JSON 字段中添加多级值,如下图所示。
我可以从其他字段中搜索数据,例如
SELECT equip_id FROM ' . $table. ' where JSON_CONTAINS(category,["1"])
我想通过 productID 搜索产品,请告诉我如何实现。
下面是我的完整图片 table
我创建了一个 table 用于测试:
mysql> select * from mytable;
+----------------------------------------------------------------------+------------+
| product | category |
+----------------------------------------------------------------------+------------+
| [{"OrderId": 1, "productID": "1"}] | ["2", "3"] |
| [{"OrderId": 2, "productID": "1"}] | ["2", "3"] |
| [{"OrderId": 3, "productID": "1"}] | ["2", "3"] |
| [{"OrderId": 4, "productID": "1"}] | ["2", "3"] |
| [{"OrderId": 5, "productID": "1"}] | ["2", "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 |
+-------------------+
我用以下数据创建了一个临时文件 table。
当我对上面的集合使用下面的查询时的输出
select * from table_name where json_contains(product, '{"productID" : "1"}')
我想从 JSON 字段中搜索产品 ID,但无法从 JSON 字段中搜索。在 JSON 字段中添加多级值,如下图所示。
我可以从其他字段中搜索数据,例如
SELECT equip_id FROM ' . $table. ' where JSON_CONTAINS(category,["1"])
我想通过 productID 搜索产品,请告诉我如何实现。
下面是我的完整图片 table
我创建了一个 table 用于测试:
mysql> select * from mytable;
+----------------------------------------------------------------------+------------+
| product | category |
+----------------------------------------------------------------------+------------+
| [{"OrderId": 1, "productID": "1"}] | ["2", "3"] |
| [{"OrderId": 2, "productID": "1"}] | ["2", "3"] |
| [{"OrderId": 3, "productID": "1"}] | ["2", "3"] |
| [{"OrderId": 4, "productID": "1"}] | ["2", "3"] |
| [{"OrderId": 5, "productID": "1"}] | ["2", "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 |
+-------------------+
我用以下数据创建了一个临时文件 table。
当我对上面的集合使用下面的查询时的输出
select * from table_name where json_contains(product, '{"productID" : "1"}')