【问题标题】:How to filter two properties in the JSON - mysql?如何过滤 JSON - mysql 中的两个属性?
【发布时间】:2018-07-08 05:05:06
【问题描述】:

我在mysql表statistics中有关注JSON format,列是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的记录。

任何建议将不胜感激。

【问题讨论】:

    标签: mysql sql json mysql-json


    【解决方案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

    【讨论】:

    • 我认为这个解决方案不起作用?根据 db-fiddle,它返回了两个城市。我错过了什么吗?
    猜你喜欢
    • 2019-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-16
    • 2019-01-18
    • 2012-06-20
    相关资源
    最近更新 更多