简体   繁体   中英

Multiple Joins with Count on the same table

I'm trying to run a usage report. Basically there is a transaction log table that records every action taken against the database from the website.

i have three tables:

**organization:**
id
name

**people:**
id
organization_id

**transaction_log:**
id
people_id
table
action

Now, lets say I have 4 other tables that users create records in, those would look like this in the transaction_log:

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

What I want: I want a result that looks something like this:

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

Currently i've been doing this one query at a time (one for each table), but we have a lot more than 4 tables so it'd be nice if i could make it run all at once. Here is what I already have:

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

When i try and add just another left join the numbers get way wrong. I did that by doing:

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

I believe it would work to first count the actions per person for each table in subqueries. Left join to each subquery result and summarize on total action count. I think your issue is that there could be many actions per people_id on each table.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM