2017-02-24 1 views
0

Ich versuche, einen Verwendungsbericht auszuführen. Grundsätzlich gibt es eine Transaktionsprotokolltabelle, die jede Aktion aufzeichnet, die von der Website gegen die Datenbank ausgeführt wird.Mehrere Joins mit Count auf derselben Tabelle

Ich habe drei Tabellen:

**organization:** 
id 
name 

**people:** 
id 
organization_id 

**transaction_log:** 
id 
people_id 
table 
action 

wir nun an, ich 4 weitere Tabellen, die Benutzer erstellen Datensätze, die wie dies in der transaction_log aussehen:

{id: 1, people_id: 33, table: "tablea", action: "create"} 
{id: 2, people_id: 44, table: "tableb", action: "create"} 

Was ich wollen: Ich möchte ein Ergebnis, das in etwa so aussieht:

{organization_id: 1, name: "some org", tbla_count: 2000, tblb_count: 3000}, 
{organization_id: 2, name: "other org", tbla_count: 100, tblb_count:100} 

Momentan mache ich diese eine Abfrage auf einmal (eine für jede Tabelle), aber wir haben viel mehr als 4 Tabellen, also wäre es schön, wenn ich es auf einmal laufen lassen könnte. Hier ist, was ich bereits habe:

Wenn ich versuche, nur einen weiteren linken Join hinzuzufügen, kommen die Zahlen falsch. Ich habe das getan:

Antwort

0

Ich glaube, es würde funktionieren, zuerst die Aktionen pro Person für jede Tabelle in Unterabfragen zu zählen. Linke Verknüpfung zu jedem Unterabfrageergebnis und Zusammenfassung der Gesamtzahl der Aktionen. Ich denke, Ihr Problem besteht darin, dass pro Person_id auf jedem Tisch viele Aktionen möglich sind.

select 
    p.organization_id, 
    sum(tl.action_count) as tbla_count 
    sum(t2.action_count) as tblb_count 
from 
    people p 
LEFT JOIN 
    (select people_id, count(action) as action_count 
    from transaction_log 
    where table = 'tablea' and action = 'create' group by people_id) tl 
ON p.id = tl.people_id 
LEFT JOIN 
    (select transaction_log people_id, count(action) as action_count 
    from transaction_log 
    where table = 'tableb' and action = 'create' group by people_id) t2 
ON p.id = t2.people_id 
GROUP BY 
    p.organization_id 
ORDER BY 
    p.organization_id