简体   繁体   中英

MySQL query related entities from multiple child rows into json array

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:

杰森结果1

Which seems pretty difficult for a client to work with. How can I convert it into a format like this?

杰森结果2

SQLFIDDLE: http://sqlfiddle.com/#!9/9bc2ebf/3

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM