mysql - MySQL 8+ JSON 查询从数组中提取一个值
问题描述
我正在尝试各种可能性来提取包含数组的 JSON 列中的单个元素。让我举个例子:
Database:
id | info
---------
1 |{"name": "aaa", "colors": ["a","b"]}
2 |{"name": "bbb", "colors": ["c","d"]}
3 |{"name": "ccc", "colors": ["e","f"]}
我需要的是有一个类似的查询,比如:
select name, color from info where color = a;
这应该返回:
"aaa", "a"
我被卡住的问题是我无法在没有固定索引的情况下在数组中搜索,但我需要能够在没有固定索引的情况下查询数据库。
解决方案
您可以使用json_search()
:
select info ->> '$.name' as name, 'a' color
from mytable
where json_search(info ->> '$.colors', 'one', 'a') is not null
推荐阅读
- c - 获得输入数字的意外输出以查找多维数据集
- sqlite - 显示多个字段 sqlite 的值而不是 id
- javascript - Javascript 自动舍入到最接近的整数
- visual-studio - 我怎样才能做到与 Visual Studio IDE 中的 gif 相同的操作?
- php - 如果 htaccess 不允许浏览文件夹,将文档存储在 public_html 下是否安全?
- reactjs - 404 与我无法在本地重现的 React 路由器
- cmake - 将 protobuf 与 CMake 的不同构建配置一起使用(RelWithDebugInfo 和 Debug)
- python - XOR 在神经网络中收敛到 0.5
- diff - 多个文件的差异和补丁
- php - 多重解析错误:PHP 代码的语法错误?