mysql - 使用 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数据的正确方法吗?
解决方案
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
推荐阅读
- php - PHP输入数组为空时不返回任何内容
- c++ - 如何手动创建将在析构函数中阻塞的未来
- python - 从张量流模型中获取预测
- javascript - Polymer 3.x、ajax 请求(到端口 8081)和 PHP 一起开发
- scala - 从 Scala 启动的进程终止,但 Scala 永远等待它的终止
- c# - 如何使用大型数据集最小化运行时间(从 93,773 个对象列表中列出唯一对象)
- go - syscall.Errno 中的字符串函数
- javascript - 如何使用输入标签中输入的颜色将背景颜色更改为线性渐变并在单击 GO 按钮后混合?
- android - 如何在 Android、Rx 中为 HTTP 204 No Content 制作测试代码
- bash - 如何确定使用哪个 .bash_profile .profile .bashrc .zshrc?