2张桌子:
Employees
- EmployeeID
- LeadCount
Leads
- leadID
- employeeID
我想Employees.LeadCount
通过计算Leads
表中具有相同EmployeeID
.
注意:可能有超过 1 个具有相同员工 ID 的潜在客户,所以我必须做一个DISTINCT(SUM(employeeID))
.
2张桌子:
Employees
- EmployeeID
- LeadCount
Leads
- leadID
- employeeID
我想Employees.LeadCount
通过计算Leads
表中具有相同EmployeeID
.
注意:可能有超过 1 个具有相同员工 ID 的潜在客户,所以我必须做一个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(*)。
UPDATE Employees SET LeadCount = (
SELECT Distinct(SUM(employeeID)) FROM Leads WHERE Leads.employeeId = Employees.employeeId
)
从上面进行钢化并删除依赖的子查询。
// 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)