使用 mysql 连接和 2 个表获取记录总数

Get total count of records with a mysql join and 2 tables

我有 2 个表要加入,但我不确定如何使其最省时。

任务Table:

nid | created_by | claimed_by | urgent
1   |     11     |     22     |   1
2   |     22     |     33     |   1
3   |     33     |     11     |   1
1   |     11     |     43     |   0
1   |     11     |     44     |   1

员工Table:

userid | name
  11   |  EmployeeA
  22   |  EmployeeB
  33   |  EmployeeC

我想要得到的结果:

userid | created_count | claimed_count | urgent_count
  11   |       3       |       1       |       3
  22   |       1       |       1       |       2
  33   |       1       |       1       |       2

created_account 列将显示该用户创建的任务总数。

claimed_count 列将显示该用户声明的任务总数。

urgent_count 列将显示该用户的紧急任务(创建或声明)总数。

提前致谢!

我会首先将其分解成多个部分,然后再将它们重新组合在一起。您可以使用这样的简单聚合获得 created_count 和 claimed_count:

SELECT created_by, COUNT(*) AS created_count
FROM myTable
GROUP BY created_by;

SELECT claimed_by, COUNT(*) AS claimed_count
FROM myTable
GROUP BY claimed_by;

为了得到每个员工的紧急计数,我会在员工是 created_by 或 claimed_by 列的条件下加入两个 tables,然后分组员工。但是,我不计算,而是使用 SUM()。我这样做是因为看起来每一行要么是 0 要么是 1,所以 SUM() 将有效地计算所有非零行:

SELECT e.userid, SUM(t.urgent)
FROM employee e
JOIN task t ON e.userid IN (t.created_by, t.claimed_by)
GROUP BY e.userid;

现在您已拥有所需的所有数据,您可以使用外部联接将所有这些子查询联接到员工 table 以获取他们的计数。您可以使用 COALESCE() 函数将任何空计数替换为 0:

SELECT e.userid, COALESCE(u.urgent_count, 0) AS urgent_count, COALESCE(crt.created_count, 0) AS created_count, COALESCE(clm.claimed_count, 0) AS claimed_count
FROM employee e
LEFT JOIN(
  SELECT e.userid, SUM(t.urgent) AS urgent_count
  FROM employee e
  JOIN task t ON e.userid IN (t.created_by, t.claimed_by)
  GROUP BY e.userid) u ON u.userid = e.userid
LEFT JOIN(
  SELECT claimed_by, COUNT(*) AS claimed_count
  FROM task
  GROUP BY claimed_by) clm ON clm.claimed_by = e.userid
LEFT JOIN(
  SELECT created_by, COUNT(*) AS created_count
  FROM task
  GROUP BY created_by) crt ON crt.created_by = e.userid;

这是一个 SQL Fiddle 示例。