mysql - 同一张表上的多个连接与计数

标签 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

最佳答案

我相信首先计算子查询中每个表的每个人的操作是可行的。左连接每个子查询结果并汇总总操作计数。我认为您的问题是每个表上的每个 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

关于mysql - 同一张表上的多个连接与计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42448395/

相关文章:

SQL:用 SQL 查找和替换?

c# - 从VisualStudio生成的数据库资料到程序员生成的资料

mysql - 如何为多个连接编写子查询sql

performance - 加速 postgres 查询(适用于 2 个表)

mysql - 有限获取所需文件

mysql - 如何在 Windows 系统上开发 Shopware 5?

php - 从日期 = 今天的表中选择 *

mysql - SQL使用COUNT(和GROUP BY?)在SELECT中执行计算而不排除记录

python - django-使文件字段可选时出错

mysql - 如何计算连接表上的行数