2桌:
Employees - EmployeeID - LeadCount Leads - leadID - employeeID
我想Employees.LeadCount
通过计算Leads
表中具有相同的引导数来更新列EmployeeID
.
注意:可能有超过1个具有相同employeeID的潜在客户,所以我必须做一个DISTINCT(SUM(employeeID))
.
UPDATE Employees E SET E.LeadCount = ( SELECT COUNT(L.EmployeeID) FROM Leads L WHERE L.EmployeeID = E.EmployeeID )
您正在为数据同步问题做好准备.在插入,更新或删除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;
联接对更新(和删除)的作用相同,就像对选择(编辑:在某些流行的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 像MySql一样支持UPDATE ... FROM和DELETE ... FROM语法,但SQL-92标准不支持。SQL-92将让您使用行表达式。我知道DB2支持此语法,但不确定其他语法。坦率地说,我发现SQL-92版本令人困惑-但是标准和理论上的疑问会指出FROM语法违反了关系理论,并且使用不精确的JOIN子句或切换RDBMS供应商时可能导致不可预测的结果。