gpt4 book ai didi

mysql - 遍历数组的 mysql JSON 路径的正确语法?

转载 作者:行者123 更新时间:2023-11-29 01:11:07 24 4
gpt4 key购买 nike

我的问题是关于在mysql的JSON数据类型中搜索时搜索json数组的内容。

数据库结构

所以,如果我在 mysql 表中有两行,带有一个名为 foo 的 json 字段。

第一行有:

{
"items": [
{"type": "bar"}
]
}

第二行有:

{
"items": [
{"type": "baz"}
]
}

有用的东西

我能跑

select `foo`->"$.items[0].type" from `jsontest`

返回 2 个结果:barbaz

我能跑

select `id` from `jsontest` where `foo`->"$.items[0].type" = "bar"

返回 1 个结果:1 - 即。第一行的id。

我的问题

mysql docs state您可以使用 [*] 来“评估 JSON 数组中所有元素的值”。

但是,以下查询返回零项:

select `id` from `jsontest` where `foo`->"$.items[*].type" = "bar"

我的查询有什么问题?

最佳答案

进行以下查询:

select id, `foo`->"$.items[*].type[0]" from `jsontest`;

您会注意到返回值显示为“[bar]”,这是 JSON 数组。

select * from `jsontest` 
where `foo`->"$.items[*].type" = JSON_ARRAY('bar');

无论如何,下面的查询也应该有效:

select id from `jsontest` where JSON_SEARCH(`foo`, 'all','bar') is not null;

关于mysql - 遍历数组的 mysql JSON 路径的正确语法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38657793/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com