How to select the columns for INNER JOIN table depending on values of the joined arrays

前端 未结 2 1092
半阙折子戏
半阙折子戏 2021-01-21 18:22

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

相关标签:
2条回答
  • 2021-01-21 19:12

    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"
    
    0 讨论(0)
  • 2021-01-21 19:19
    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

    0 讨论(0)
提交回复
热议问题