2017-02-24 85 views
0

我正在嘗試運行使用情況報告。基本上有一個事務日誌表,記錄從網站對數據庫採取的每一個行動。在同一張桌面上計算多個連接

我有三個表:

**organization:** 
id 
name 

**people:** 
id 
organization_id 

**transaction_log:** 
id 
people_id 
table 
action 

現在,可以說我有用戶創建的記錄中,那些看起來像這樣在transaction_log 4個其他表:

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

我想要: 我想要一個看起來像這樣的結果:

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

目前我一直在做這一個查詢(每個表有一個查詢),但是我們有4個以上的表,所以如果我可以一次運行它,它會很好。這裏是我已經有:

select 
    p.organization_id, 
    count(tl.action) as tbla_count 
from 
    people p 
LEFT JOIN 
    transaction_log tl ON p.id = tl.people_id AND tl.table = 'tablea' and tl.action = 'create' 
GROUP BY 
    p.organization_id 
ORDER BY 
    p.organization_id 

當我嘗試和添加只是另一個左連接數字會出錯。我是這樣做的:

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

回答

0

我相信它會首先計算子查詢中每個表的行爲。左連接到每個子查詢結果並總計總操作數。我認爲你的問題是每個表上每個people_id可能會有很多操作。

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