我正在尝试各种可能性来提取包含数组的JSON列中的单个元素。 让我举个例子:
Database:
id | info
---------
1 |{"name": "aaa", "colors": ["a","b"]}
2 |{"name": "bbb", "colors": ["c","d"]}
3 |{"name": "ccc", "colors": ["e","f"]}
我需要一个类似的查询,比如:选择名称,颜色从信息中选择,颜色=a;
这应该返回:“aaa”,“a”
我遇到的问题是,如果没有fix索引,我无法在数组中搜索,但是我需要能够在没有fix索引的情况下查询数据库。
您可以使用json_search()
:
select info ->> '$.name' as name, 'a' color
from mytable
where json_search(info ->> '$.colors', 'one', 'a') is not null
SELECT info->"$.name" AS `name`
FROM test
WHERE JSON_CONTAINS(info, '"a"', '$.colors');