首页 > 解决方案 > 使用 id 查询 MySQL 中的 JSON 列

问题描述

我在 MySQL 中有一个表,列中的数据格式如下:

[{"type_id":1,"price":50},{"type_id":3,"price":60}]

我需要根据商品的 ID 找出商品的价格。例如,我需要找出 type_id = 3 的商品的价格

我试过了:

select JSON_EXTRACT(JSONColumn, '$[*].price') as prices, JSON_EXTRACT(JSONColumn, '$[*].type_id') as quantities from Items where ItemId = 123
and json_contains(JSONColumn, '{"type_id" : 3}')

这是行不通的。有人可以指定查询json数据的正确方法吗?

标签: mysqljson

解决方案


SELECT test.id, jsontable.price
FROM test
CROSS JOIN JSON_TABLE (test.val,
                       '$[*]' COLUMNS (type_id INT PATH '$.type_id',
                                       price INT PATH '$.price')) jsontable
WHERE jsontable.type_id = 3;

https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=baa0a24a4bbf10ba30202c7156720018


推荐阅读