我有两张桌子,我想加入,但我不知道如何让它最有效率。
任务表:
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
列将显示该用户声明的总任务数。
test/15-test
列将显示该用户的紧急任务总数(已创建或已声明)。
提前致谢!
答案 0 :(得分:0)
我首先将它分解成碎片,然后将它们重新组合在一起。您可以使用这样的简单聚合获取created_count和claims_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或claim_by列,并且是员工。但是,我会使用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;
现在您拥有了所需的所有数据,您可以使用外部联接将所有这些子查询连接到employees表以获取其计数。您可以使用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示例。