我在 mysql 表中有以下JSON format
statistics
,列stats
{
"stats":{
"gender":{
"male":40, //40 is percentage
"female":50
},
"cities":[
{
"name":"Melbourne",
"country":"AU",
"percentage":20
},
{
"name":"London",
"country":"GB",
"percentage":10
},
{
"name":"Sydney",
"country":"AU",
"percentage":14
}
]
}
}
我所知道的(使用 -> 或 JSON_EXTRACT(:
select * from statistics as a where a.stats->'$.stats.gender.male' < 41
It returns the above row since male percentage is 40.
要求:
我需要获取国家/地区 AU 和百分比20 的记录。
任何建议将不胜感激。
一种选择是使用JSON_CONTAINS函数。
测试:
SET @`country` := '"AU"',
@`percentage` := '20';
SELECT
`stats`,
`a`.`stats` -> '$.stats.cities[*].country',
`a`.`stats` -> '$.stats.cities[*].percentage'
FROM
`statistics` `a`
WHERE
JSON_CONTAINS(`a`.`stats` -> '$.stats.cities[*].country', @`country`) AND
JSON_CONTAINS(`a`.`stats` -> '$.stats.cities[*].percentage', @`percentage`);
参见数据库小提琴。