2张表:
Employees
- EmployeeID
- LeadCount
Leads
- leadID
- employeeID
我想通过计算Employees.LeadCount
表中具有相同Leads
的潜在客户数来更新EmployeeID
列。
注意:同一个employeeID可能有多个潜在客户,因此我必须执行DISTINCT(SUM(employeeID))
。
答案 0 :(得分:12)
UPDATE
Employees E
SET
E.LeadCount = (
SELECT COUNT(L.EmployeeID)
FROM Leads L
WHERE L.EmployeeID = E.EmployeeID
)
答案 1 :(得分:9)
您正在为自己设置数据同步问题。在插入,更新或删除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;
答案 2 :(得分: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(*)。
答案 3 :(得分:1)
UPDATE Employees SET LeadCount = (
SELECT Distinct(SUM(employeeID)) FROM Leads WHERE Leads.employeeId = Employees.employeeId
)
答案 4 :(得分: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)