简体   繁体   中英

Trigger to update a count based on another table

I am working on a php project for managing employees.
i have two tables employee and department with the department number being a relation between the two. department has an attribute that contains a count of employees based on the deparment number.
So where i'm stuck is that i want the employee count to be automatically inserted, so what do you think i should do

Thanks in advance

Instead of storing and updating the value each time something is changed you should just calculate it when needed.
You can use count to do it.

Example

SELECT department_number, count(*) FROM employee GROUP BY department_number

If you don't want to use (or have access to) a trigger, but want to abstract the logic, you could use a view ( docs ).

So assuming the below data, and the idea of having the entire department table and the employee count dynamically calculated, you could have the following query:

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);

Then the query:

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 

Gives the result:

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

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

So to create this view, you could use:

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 

Then you could call the view as:

SELECT
    *
FROM
    `departments_employee_count`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM