Op basis van mijn begrip, hier is de vraag die ik bedenk:
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
De uitsplitsing van de zoekopdracht:
#1. De leden-ID ophalen met het bijbehorende aantal doelen (innerQuery)
SELECT m.id memberId, COUNT(*) goalsCount
FROM Members m
JOIN Goals g
ON m.id = g.member_id
GROUP BY member_id
#2. Verkrijg de team-ID voor met de totale SUM van de doelen (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. Krijg het totale aantal leden per team (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. RECHTS JOIN inner_1 en inner_2 (aangezien er NULL zal zijn) en gebruik IFNULL om die 0 te controleren en te vervangen
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