在同一个表上使用Count连接多个连接

时间:2017-02-24 21:14:10

标签: mysql sql join

我正在尝试运行使用情况报告。基本上有一个事务日志表,记录从网站对数据库采取的每个操作。

我有三张桌子:

**organization:**
id
name

**people:**
id
organization_id

**transaction_log:**
id
people_id
table
action

现在,假设我有其他4个用户创建记录的表,这些表在transaction_log中看起来像这样:

{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

1 个答案:

答案 0 :(得分: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