sql >> Database >  >> RDS >> Mysql

Hoe arrays samen te voegen met MySQL vanuit 3 tabellen met veel-op-veel-relaties

De "eazy" methode is om CONCAT te gebruiken om JSON te genereren.
En gebruik GROUP_CONCAT om de records van meerdere teams te combineren in een JSON-array.
Deze methode werkt ook in de oudere MySQL-versies die geen ondersteuning bieden voor het maken van JSON-functies.

Zoekopdracht

SET SESSION group_concat_max_len = @@max_allowed_packet

SELECT 
 CONCAT(
     "{"
   ,     '"id"' , ":" , '"' , friends.id , '"' , ","
   ,     '"name"' , ":" , '"' , friends.name , '"' , ","
   ,     '"team"' , ":" , "["
                              , GROUP_CONCAT('"', teams.name, '"')
                        , "]"
   , "}"
   ) AS json
FROM 
 friends 
INNER JOIN 
 relations 
ON 
 friends.id = relations.friends_id
INNER JOIN
 teams 
ON
 relations.teams_id = teams.id
WHERE 
 friends.id = 1

Resultaat

|                                                            json |
|-----------------------------------------------------------------|
| {"id":"1","name":"David Belton","team":["Cleveland Cavaliers"]} |

demo

http://www.sqlfiddle.com/#!9/4cd244/19

Meer vrienden bewerkt

Zoekopdracht

SET SESSION group_concat_max_len = @@max_allowed_packet

SELECT
  CONCAT(
      "["
    , GROUP_CONCAT(json_records.json) # combine json records into a string
    , "]"
  )  AS json
FROM (

  SELECT 
     CONCAT(
       "{"
     ,     '"id"' , ":" , '"' , friends.id , '"' , ","
     ,     '"name"' , ":" , '"' , friends.name , '"' , ","
     ,     '"team"' , ":" , "["
                              , GROUP_CONCAT('"', teams.name, '"')
                          , "]"
     , "}"
     ) AS json 
  FROM 
    friends 
  INNER JOIN 
    relations 
  ON 
    friends.id = relations.friends_id
  INNER JOIN
    teams 
  ON
    relations.teams_id = teams.id
  WHERE 
    friends.id IN(SELECT id FROM friends) #select the friends you need or just simply friends.id IN(1, 2)
  GROUP BY
     friends.id
) 
 AS json_records

Resultaat

|                                                                                                                                             json |
|--------------------------------------------------------------------------------------------------------------------------------------------------|
| [{"id":"1","name":"David Belton","team":["Cleveland Cavaliers"]},{"id":"2","name":"Alex James","team":["Boston Celtics","Cleveland Cavaliers"]}] |

demo

http://www.sqlfiddle.com/#!9/4cd244/61




  1. Controleer welke gebruikers online zijn

  2. dBase-ondersteuning is terug in Microsoft Access!

  3. Stel lege strings ('') in op NULL in de hele database

  4. INSERT met LIST in Opgeslagen procedure