我有一个带有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}}
答案 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)