Reputation: 31
i have a query with a group by statement and i want to transform that data in a proper json object
query:
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
expected result:
{canada: {count: 1565}, colombia: {count:15645612}}
Upvotes: 2
Views: 731
Reputation: 1667
"select return JSON
", there are two ways of doing this :
Upvotes: 0
Reputation: 1
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;
Upvotes: 0
Reputation: 222512
You can add a level of aggregation and use json_objectagg()
(available starting 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
Upvotes: 2