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