Mysql json datatype count and groupby

前端 未结 1 1166
遥遥无期
遥遥无期 2021-02-09 13:40

So since mysql 5.7 i am now able to use the json datatype which is nice when your working with frameworks like angularjs.

Now since im fairly new to this (and this datat

相关标签:
1条回答
  • 2021-02-09 14:00

    Firstly you are storing all the JSON in one row, if you want to query the data like this each resident should have it's own row of his/her own JSON:

    *other_fields*, {"A": 1, "B": "Debra", "C": "Peters", "D": "dpeters0@accuweather.com", "E": "Female", "F": "Tsagaan-Ovoo"}
    *other_fields*, {"A": 2, "B": "Marc", "C": "Rasmussen", "D": "Marc@test.dk", "E": "Male", "F": "Copenhagen"}
    

    Secondly you don't need to count the extracted data, you just need to count the rows for each country extracted. This will do:

    SELECT JSON_EXTRACT(data, "$.F") AS country,
           COUNT(*) AS num_residents
    

    Thirdly, you don't want to GROUP BY data at all as this is presumably unique per resident. This will leave you with a group for each row. I think you just want:

    GROUP BY country
    

    Putting it all together:

      SELECT JSON_EXTRACT(data, "$.F") AS country,
             COUNT(*) AS num_residents
        FROM kpi_data
       WHERE schema_id = 39
    GROUP BY country
    

    For decent performance, you may consider placing an secondary index on the extracted country.. see DOCS

    0 讨论(0)
提交回复
热议问题