如何在JSON中过滤两个属性 - mysql?

时间:2018-01-29 13:24:58

标签: mysql sql json mysql-json

我在mysql表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 } ] } }

select * from statistics as a where a.stats->'$.stats.gender.male' < 41

It returns the above row since male percentage is 40.

我所知道的(使用 - &gt;或JSON_EXTRACT):

Eclipse

要求:

我需要提取国家 AU 百分比 20 的记录。

任何建议都将不胜感激。

1 个答案:

答案 0 :(得分:1)

一种选择是使用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`);

请参阅db-fiddle

相关问题