I created a mySQL database with phpMyAdmin in my local server. In this database I store the names and the favourite NBA teams of my friends.This is obviously a many-to-many rela
For these type of query you have to use the mysql version 5.7 using these you are able to use the json type & function in query..
Answer :
SELECT GROUP_CONCAT( JSON_OBJECT(
'id', f.id, 'fname', f.name, 'tname', t.name, 'current_status', r.status), (SELECT JSON_OBJECT('name', tm.name)
FROM teams tm, relations re
WHERE tm.id = re.teams_id
AND f.id = re.friends_id
AND re.status = "Past"))
FROM teams t, relations r, friends f
WHERE t.id = r.teams_id
AND f.id = r.friends_id
AND r.status = "Current"
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