8

2张桌子:

Employees
- EmployeeID
- LeadCount


Leads
- leadID
- employeeID

我想Employees.LeadCount通过计算Leads表中具有相同EmployeeID.

注意:可能有超过 1 个具有相同员工 ID 的潜在客户,所以我必须做一个DISTINCT(SUM(employeeID)).

4

5 回答 5

12
UPDATE
    Employees E
SET
    E.LeadCount = (
        SELECT COUNT(L.EmployeeID)
        FROM Leads L
        WHERE L.EmployeeID = E.EmployeeID
    )
于 2008-09-26T00:02:12.653 回答
10

您正在为数据同步问题做好准备。随着 Leads 表中的行被插入、更新或删除,您需要不断更新 Employees.LeadCount 列。

最好的解决方案是根本不存储 LeadCount 列,而是根据需要使用 SQL 聚合查询重新计算潜在客户数。这样它永远是正确的。

SELECT employeeID, COUNT(leadId) AS LeadCount
FROM Leads
GROUP BY employeeID;

另一种解决方案是在 Leads 表上为 INSERT、UPDATE 和 DELETE 创建触发器,以便始终保持Employees.LeadCount 列最新。例如,使用 MySQL 触发器语法:

CREATE TRIGGER leadIns AFTER INSERT ON Leads
FOR EACH ROW BEGIN
  UPDATE Employees SET LeadCount = LeadCount + 1 WHERE employeeID = NEW.employeeID;
END

CREATE TRIGGER leadIns AFTER UPDATE ON Leads
FOR EACH ROW BEGIN
  UPDATE Employees SET LeadCount = LeadCount - 1 WHERE employeeID = OLD.employeeID;
  UPDATE Employees SET LeadCount = LeadCount + 1 WHERE employeeID = NEW.employeeID;
END

CREATE TRIGGER leadIns AFTER DELETE ON Leads
FOR EACH ROW BEGIN
  UPDATE Employees SET LeadCount = LeadCount - 1 WHERE employeeID = OLD.employeeID;
END

如果您使用 MySQL,另一种选择是使用多表 UPDATE 语法。这是 SQL 的 MySQL 扩展,它不能移植到其他品牌的 RDBMS。首先,将所有行中的 LeadCount 重置为零,然后对 Leads 表进行连接,并在连接产生的每一行中增加 LeadCount。

UPDATE Employees SET LeadCount = 0;
UPDATE Employees AS e JOIN Leads AS l USING (employeeID)
  SET e.LeadCount = e.LeadCount+1;
于 2008-09-26T00:26:29.630 回答
4

连接对更新(和删除)的作用与对选择的作用相同(编辑:在一些流行的 RDBMS 中,至少*):

UPDATE Employees SET
  LeadCount = Leads.LeadCount
FROM Employee
JOIN (
  SELECT EmployeeId, COUNT(*) as LeadCount 
  FROM Leads 
  GROUP BY EmployeeId
) as Leads ON
  Employee.EmployeeId = Leads.EmployeeId  

SUM(DISTINCT EmployeeId) 没有意义——你只需要一个 COUNT(*)。

  • MS SQL Server 支持UPDATE...FROMDELETE...FROM语法,MySql也是如此,但 SQL-92 标准不支持。SQL-92 会让您使用行表达式。我知道DB2支持这种语法,但不确定是否有其他语法。坦率地说,我发现 SQL-92 版本令人困惑——但标准和理论专家会争辩说,FROM 语法违反了关系理论,并且在不精确的 JOIN 子句或切换 RDBMS 供应商时可能导致不可预测的结果。
于 2008-09-26T00:24:13.660 回答
1
UPDATE Employees SET LeadCount = (
  SELECT Distinct(SUM(employeeID)) FROM Leads WHERE Leads.employeeId = Employees.employeeId
)
于 2008-09-25T23:59:37.980 回答
0

从上面进行钢化并删除依赖的子查询。

// create tmp -> TBL (EmpID, count)

insert into TBL 
   SELECT employeeID COUNT(employeeID) Di
   FROM Leads WHERE Leads.employeeId = Employees.employeeId GROUP BY EmployeeId
UPDATE Employees SET LeadCount = (
  SELECT count FROM TBL WHERE TBL.EmpID = Employees.employeeId
)

// drop TBL

编辑这是“group By”而不是“distinct”:b(感谢Mark Brackett)

于 2008-09-26T00:08:54.133 回答