Mysql
 sql >> Datenbank >  >> RDS >> Mysql

Zählen Sie Werte über m/n verbundene Tabellen in SQL

Ich denke, das würde funktionieren.

SELECT n.id,
       n.name,
       COUNT(DISTINCT l.id) AS locations,
       COUNT(DISTINCT d.id) AS downloads
FROM names n LEFT JOIN names_location nl
  ON n.id = nl.name_id
LEFT JOIN downloads dl
  ON n.id = dl.name_id
LEFT JOIN locations l
  ON l.id = nl.location_id
GROUP BY n.id, n.name