如何将mysql查询“ group by statement”结果转换为json结构?

时间:2019-12-02 13:30:02

标签: mysql sql json group-by

我有一个带有group by语句的查询,我想将数据转换为适当的json对象

查询:

SELECT c.name, count(u.id) 
FROM users AS u 
INNER JOIN contries AS c ON u.country_id = c.id 
GROUP BY c.id

预期结果:

{canada: {count: 1565}, colombia: {count:15645612}}

3 个答案:

答案 0 :(得分:2)

您可以添加聚合级别并使用json_objectagg()(从MySQL 5.7开始可用):

select json_objectagg(name, js_count) js
from (
    select c.name, json_object('count', count(u.id)) js_count
    from users as u 
    inner join contries as c on u.country_id = c.id 
    group by c.id, c.name
) t

答案 1 :(得分:0)

SELECT JSON_OBJECT(
  'name', c.name,
  'count', count(u.id)
)
FROM users as u INNER JOIN contries AS c ON u.country_id = c.id 
GROUP BY c.id;

答案 2 :(得分:0)

select return JSON”,有两种方法:

  1. 使用“ hack”-参见db-fiddle here
  2. 或在此处使用MySQL提供的新JSON函数之一-具有讽刺意味的是,它似乎比hack本身更像是hack!只有MySQL! :(小提琴here)。