首页 > 解决方案 > 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"

我被卡住的问题是我无法在没有固定索引的情况下在数组中搜索,但我需要能够在没有固定索引的情况下查询数据库。

标签: mysqlsqlarraysjsonselect

解决方案


您可以使用json_search()

select info ->> '$.name' as name, 'a' color
from mytable 
where json_search(info ->> '$.colors', 'one', 'a') is not null

推荐阅读