为不同的员工更新 managerId

Update managerId for for different employee

下面有Reporting_officersTable.structuretable

R_id    User_id Manager_id  Managre2_id
1        4       3        3
2        3       2        2
3        5       3        2

现在我想在这个 table 中更新 user_id 3 到 6,然后它应该反映到 manager_id 和 manger2_id 其中有 3 如下图

R_id    User_id   Manager_id  Managre2_id
 1          4         6           6
 2          6         2           2
 3          5         6           2

最简单的方法是使用具有 on update cascade 子句的外键定义 table,这样数据库就可以为您处理所有繁重的工作,以及您需要做的一切正在更新 user_id:

CREATE TABLE users (
    r_id int,
    user_id int,
    manager_id int,
    manager2_id int,
    PRIMARY KEY (r_id),
    CONSTRAINT users_id_uk UNIQUE (user_id)
    FOREIGN KEY users_manager_id_fk 
        FOREIGN KEY (manager_id)
        REFERENCES `users` (user_id)
        ON UPDATE CASCADE,
    FOREIGN KEY users_manager2_id_fk 
        FOREIGN KEY (manager2_id)
        REFERENCES `users` (user_id)
        ON UPDATE CASCADE
);

此查询运行良好,您可以在 sql fiddle 上查看 table strutured

table after dml

UPDATE 
  `Reporting_officers`  
SET
  `Manager_id` = NULL
WHERE Reporting_officers.`Manager_id` = 3;

UPDATE 
  `Reporting_officers`  
SET
  `Managre2_id` = NULL
WHERE `Managre2_id` = 3;


UPDATE 
  `Reporting_officers`  
SET
  User_id = 6 
WHERE `User_id` = 3;


UPDATE 
  `Reporting_officers` 
SET
  `Manager_id` = CASE WHEN Manager_id IS NULL  THEN 6 ELSE Manager_id END,
  `Managre2_id` = CASE WHEN Managre2_id IS NULL  THEN 6 ELSE Managre2_id END