当前位置:  开发笔记 > 后端 > 正文

从另一个表的行批量更新表

如何解决《从另一个表的行批量更新表》经验,为你挑选了3个好方法。

2桌:

Employees
- EmployeeID
- LeadCount


Leads
- leadID
- employeeID

我想Employees.LeadCount通过计算Leads表中具有相同的引导数来更新列EmployeeID.

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



1> Jonny Buchan..:
UPDATE
    Employees E
SET
    E.LeadCount = (
        SELECT COUNT(L.EmployeeID)
        FROM Leads L
        WHERE L.EmployeeID = E.EmployeeID
    )



2> Bill Karwin..:

您正在为数据同步问题做好准备.在插入,更新或删除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;



3> Mark Bracket..:

联接对更新(和删除)的作用相同,就像对选择(编辑:在某些流行的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供应商时可能导致不可预测的结果。

推荐阅读
oDavid_仔o_880
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有