【问题标题】:auto updated column by another column in another table由另一个表中的另一列自动更新列
【发布时间】:2017-06-17 19:05:56
【问题描述】:

我有两张表,Employee 和 Sales。 在 Employee 表中有一个名为“销售数量”的列。 但我希望它是不可插入的。 所以你不能插入任何东西,它会被另一个因素更新: 对于 Sales 中与该员工具有相同 ID 的每一列,我想查看 Employee 'number of sales' 列中的销售额。

类似于 [number of sales]=select count(*) from sales s group by employeeID where EmployeeID=s.EmployeeID

【问题讨论】:

    标签: sql sql-server


    【解决方案1】:

    通常的方法是触发(记录在here)。

    您还可以将生成的列与用户定义的函数一起使用。

    但是,我会提醒您不要使用这两种方法,因为它们可能很复杂,并且会以意想不到的方式影响性能。相反,为什么不直接创建一个视图?

    create view v_employees as
        select e.*, s.cnt
        from employees e outer apply
             (select count(*) as cnt
              from sales s 
              where s.EmployeeID = e.EmployeeID
             ) s;
    

    您可以在需要时查询视图并获取值。当sales 中的值因插入、更新和删除而发生变化时,该值会自动“更新”。

    【讨论】:

      猜你喜欢
      • 2013-08-26
      • 2011-04-18
      • 2022-01-23
      • 1970-01-01
      • 1970-01-01
      • 2016-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多