2017-10-25 1 views
0

die 4 einfachen Tabellen Lassen Sie haben:MySQL-Abfrage mit mehreren Zählung Anweisungen in einer effektiven Art und Weise

TABLE region (id, name) 
TABLE country (id, name, region_id) 
TABLE organization (id, name, country_id) 
TABLE person (id, name, organization_id) 

Ich möchte eine Abfrage machen, wo ich hätte:

  • Region Name
  • Person Anzahl für die Region
  • Ländername
  • Anzahl der Personen für das Land
  • Name der Organisation
  • Person für Organisation zählen
  • Person Name

Zum Beispiel: Europa, 20, Slowakei, 2, Universität des Lebens, 1, Jemand

Wie kann ich die machen zählt effektiv in MySQL?

Ich habe eine riesige Abfrage, wo ich für jede Zählung inline wählt, aber das ist überhaupt nicht effizient. Ich erwäge Summe mit Fall, aber ich verstehe nicht ganz das Konzept begreifen, wenn ich Tausende von Organisationen mit unterschiedlichen Namen haben ...

Antwort

0
SELECT r.name as region, count(DISTINCT r.id) as region_total, 
     c.name as city, count(DISTINCT c.id) as country_total, 
     o.name as organization, count(DISTINCT o.id) as organization_total, 
     COUNT(p.id) as person_total 
FROM region r 
JOIN country c 
    on r.id= c.region_id 
JOIN organization o 
    ON c.id = o.country_id 
JOIN person p 
    ON o.id p.organization_id 
GROUP BY r.id, c.id, o.id 
ORDER BY r.id, c.id, o.id 

Ich sehe nicht, wie man eine Person Namen aufnehmen möchten hier

Verwandte Themen