【发布时间】:2020-12-29 11:46:11
【问题描述】:
我有这张桌子
id name json
1 alex {"type": "user", "items": [ {"name": "banana", "color": "yellow"}, {"name": "apple", "color": "red"} ] }
2 peter {"type": "user", "items": [ {"name": "watermelon", "color": "green"}, {"name": "pepper", "color": "red"} ] }
3 john {"type": "user", "items": [ {"name": "tomato", "color": "red"} ] }
4 carl {"type": "user", "items": [ {"name": "orange", "color": "orange"}, {"name": "nut", "color": "brown"} ] }
重要的是,每个 json 对象可以有不同数量的“项目”,但我需要的是在 WHERE 条件下匹配的对象的“产品名称”。
我想要的输出是前两列和项目的名称,其中颜色类似于 %red%:
id name fruit
1 alex apple
2 peter pepper
3 john tomato
select id, name, ***** (this is what I don't know) FROM table
where JSON_EXTRACT(json, "$.items[*].color") like '%red%'
【问题讨论】:
-
那个 JSON 有效吗?我不这么认为!不是必须的吗??我想是的!
-
这不是有效的 JSON。
"items"应该有方括号,而不是大括号。"items: [ {"name": "banana", "color": "yellow"}, ... ]. -
假设 JSON 在一个 JSON 值中包含 2 个带有红色的水果 - 在这种情况下您希望看到什么输出?
-
您是如何创建插入数据库的 JSON 的?看来代码需要先修复
-
对不起!我是在飞行中创建的......它是无效的,对不起,但这只是为了得到这个想法
标签: sql arrays json mariadb mariadb-10.5