Mysql
 sql >> Datenbank >  >> RDS >> Mysql

So wählen Sie die Spalten für die INNER JOIN-Tabelle in Abhängigkeit von den Werten der verknüpften Arrays aus

SELECT 
   CONCAT( 
    "{"
   ,     '"id"' , ":" , '"' , friends.id , '"' , ","
   ,     '"name"' , ":" , '"' , friends.name , '"' , ","
    , 
   CASE 
   WHEN relations.status = 'Current' 
     THEN CONCAT('"CurrentTeam":["',    teams.name ,'"]')
   ELSE CONCAT('"pastTeam": '   ,   '[' ,   GROUP_CONCAT( '"',teams.name, '"'),']'  )
     END   
   , "}"
   )
  AS json
FROM 
 friends 
INNER JOIN 
 relations 
ON 
 friends.id = relations.friends_id
INNER JOIN
 teams 
ON
relations.teams_id = teams.id
 group by friends.id,relations.status

http://sqlfiddle.com/#!9/694bc69/23