Reputation: 973
This is my databasedesign with a many-to-many relation
table Tournament
TournamentId int
name varchar(45)
table User
UserId int
name varchar(45)
table Tournament_Users
Tournament_Id int
User_Id int
I am attempting to return all tournaments with a list of the tournament's users in a JSON format. I'm not sure if this is possible to do in the query or it's a javascript job? I tried to follow this Returning child rows formatted as JSON in SQL Server queries but I drowned in the example.
This is my current query
SELECT t.TournamentId, t.Name as tourName, u.UserId, u.Name as userName
FROM Tournament_Users tu
LEFT JOIN Tournaments t ON tu.Tournament_Id = t.TournamentId
LEFT JOIN Users u ON u.UserId = tu.User_Id
So as a json result this looks like this:
Which seems pretty difficult for a client to work with. How can I convert it into a format like this?
SQLFIDDLE: http://sqlfiddle.com/#!9/9bc2ebf/3
Upvotes: 0
Views: 2598
Reputation: 16551
Try something like:
SELECT
CONCAT('{"data": [', GROUP_CONCAT(`json`), ']}') `json`
FROM (
SELECT
JSON_OBJECT(
'TournamentId', `t`.`TournamentId`,
'tourName', `t`.`Name`,
'users', JSON_ARRAYAGG(
JSON_OBJECT(
'UserId', `u`.`UserId`,
'userName', `u`.`Name`
)
)
) `json`
FROM
`Tournament_Users` `tu`
LEFT JOIN
`Tournaments` `t` ON `tu`.`Tournament_Id` = `t`.`TournamentId`
LEFT JOIN
`Users` `u` ON `u`.`UserId` = `tu`.`User_Id`
GROUP BY `t`.`TournamentId`, `t`.`Name`
ORDER BY `t`.`TournamentId`
) `der`;
See db-fiddle.
Upvotes: 1
Reputation: 1041
If you are using mysql 8.0 then
SELECT json_object(
'TournamentId', t.TournamentId ,'tourName', t.Name ,'UserId' ,u.UserId, 'UserName' ,u.Name)
FROM Tournament_Users tu
LEFT JOIN Tournaments t ON tu.Tournament_Id = t.TournamentId
LEFT JOIN Users u ON u.UserId = tu.User_Id
You can refer -https://dev.mysql.com/doc/refman/8.0/en/json-creation-functions.html
Upvotes: 0