Mysql
 sql >> Database >  >> RDS >> Mysql

Query MySQL:unisci 3 tabelle insieme, raggruppa per una colonna e conta per le altre 2

Sulla base della mia comprensione, ecco la domanda che mi viene in mente:


    SELECT name, membersCount, IFNULL(totalCount, 0) goalsCount FROM
    (
      SELECT m.team_id, SUM(innerQuery.goalsCount) totalCount
      FROM (
        SELECT m.id memberId, COUNT(*) goalsCount
        FROM Members m
        JOIN Goals g
        ON m.id = g.member_id
        GROUP BY member_id
      ) innerQuery
      JOIN Members m
      ON innerQuery.memberId = m.id
      GROUP BY m.team_id
    ) inner_1
    RIGHT JOIN 
    (
      SELECT t.id, t.name, COUNT(*) membersCount
      FROM Teams t
      JOIN Members m
      ON t.id = m.team_id
      GROUP BY team_id
    ) inner_2
    ON inner_1.team_id = inner_2.id

La suddivisione della query:

# 1. Ottieni l'ID membro con il conteggio degli obiettivi associati (innerQuery)


SELECT m.id memberId, COUNT(*) goalsCount
    FROM Members m
    JOIN Goals g
    ON m.id = g.member_id
    GROUP BY member_id

#2. Ottieni l'ID della squadra con la SOMMA totale degli obiettivi (inner_1)


     SELECT m.team_id, SUM(innerQuery.goalsCount) totalCount
      FROM (
          .... Sub-query in step 1
      ) innerQuery
      JOIN Members m
      ON innerQuery.memberId = m.id
      GROUP BY m.team_id

#3. Ottieni il conteggio totale dei membri per squadra (inner_2)


    SELECT t.id, t.name, COUNT(*) membersCount
      FROM Teams t
      JOIN Members m
      ON t.id = m.team_id
      GROUP BY team_id

#4. RIGHT JOIN inner_1 e inner_2 (poiché ci sarà NULL) e usa IFNULL per controllare e sostituire quello 0


    SELECT name, membersCount, IFNULL(totalCount, 0) goalsCount FROM
    (
     .... Sub-query in step 2
    ) inner_1
    RIGHT JOIN 
    (
      .... Sub-query in step 3
    ) inner_2
    ON inner_1.team_id = inner_2.id