触发根据另一个表更新计数

时间:2017-11-08 12:47:16

标签: php mysql

我正在开发一个用于管理员工的php项目 我有两个表employeedepartment,部门编号是两者之间的关系。 department有一个属性,其中包含基于部门编号的员工数量 所以,我被困在哪里,我希望自动插入员工数量,所以你认为我应该做什么

提前致谢

2 个答案:

答案 0 :(得分:0)

每次更改某些内容时,您应该只在需要时计算它,而不是存储和更新值 您可以使用count来执行此操作。

实施例

vars <- ls()
evalq(f(), envir = e)
new_vars <- ls()
rm(list = new_vars[!new_vars %in% vars])

答案 1 :(得分:0)

如果您不想使用(或有权访问)触发器,但想要抽象逻辑,则可以使用视图(docs)。

因此,假设以下数据以及动态计算整个部门表和员工计数的想法,您可以进行以下查询:

CREATE TABLE
  `employees`
(
   `employeeID` INT PRIMARY KEY AUTO_INCREMENT,
   `name` VARCHAR(50),
   `department_number` INT
);

CREATE TABLE
  `departments`
(
  `department_number` INT PRIMARY KEY AUTO_INCREMENT,
  `name` VARCHAR(50)
);

INSERT INTO 
   `departments`
(`department_number`, `name`)
VALUES
(1, 'Tech Department'),
(2, 'Admin Department');

INSERT INTO
  `employees`
(`name`, `department_number`)
VALUES
('John Doe', 1),
('Jane Doe', 1),
('Jimmy Doe', 2);

然后查询:

SELECT
    DepartmentTbl.*,
    DepartmentEmployeeTbl.employee_count
FROM
  `departments` AS DepartmentTbl
LEFT JOIN
  (
   SELECT
      `department_number`,
      COUNT(`employeeID`) AS `employee_count`
    FROM
      `employees`
    GROUP BY
      `department_number`
   ) AS DepartmentEmployeeTbl
   ON DepartmentTbl.department_number = DepartmentEmployeeTbl.department_number 

给出结果:

department_number | name              | employee_count
-------------------------------------------------------
1                 | Tech Department   | 2
2                 | Admin Department  | 1

SQLFiddle - http://sqlfiddle.com/#!9/3e0b54/1

因此,要创建此视图,您可以使用:

CREATE OR REPLACE VIEW `departments_employee_count` AS
SELECT
        DepartmentTbl.*,
        DepartmentEmployeeTbl.employee_count
    FROM
      `departments` AS DepartmentTbl
    LEFT JOIN
      (
       SELECT
          `department_number`,
          COUNT(`employeeID`) AS `employee_count`
        FROM
          `employees`
        GROUP BY
          `department_number`
       ) AS DepartmentEmployeeTbl
       ON DepartmentTbl.department_number = DepartmentEmployeeTbl.department_number 

然后您可以将视图称为:

SELECT
    *
FROM
    `departments_employee_count`