简体   繁体   English

使用自连接子查询更新

[英]Update with self join subquery

Question: 题:

A supervisor ( employee_id equals to 114 ) has resigned from the company, and today is the last day of work. 主管( employee_id等于114 )已从公司辞职,今天是工作的最后一天。 With immediate effect, the department he manages, and all those employees he supervises will be taken over by his supervisor 从即日起,他所管理的部门以及他所监督的所有员工将由其主管接管。

So my syntax i came up with is: 所以我想出的语法是:

UPDATE EMPLOYEE
   SET supervisor_id = (SELECT supervisor_id
                          FROM EMPLOYEE
                         WHERE employee_id = '114'),
 WHERE supervisor_id = '114';

OUTPUT: ERROR 1093 (HY000): You can't specify target table 'EMPLOYEE' for update in FROM clause 输出:错误1093(HY000):您无法在FROM子句中指定目标表“ EMPLOYEE”进行更新

but its wrong. 但这是错误的。 I know the supervisor_id = 100 however i do not just want to put SET supervisor_id = 100 as it doesn't seem fair to put 100 directly . 我知道supervisor_id = 100但是我不只是想放SET supervisor_id = 100因为直接100不公平。 Can anyone help me correct? 谁能帮我纠正?

UPDATE EMPLOYEE a 
  join 
     ( SELECT supervisor_id
            , employee_id  
         FROM EMPLOYEE 
        WHERE employee_id = '114'
     ) b 
    on a.supervisor_id = b.employee_id 
   set a.supervisor_id = b.supervisor_id 

use this query 使用此查询

In MySQL you can't reference same table for INSERT/UPDATE/DELETE . 在MySQL中,您不能为INSERT/UPDATE/DELETE引用同一表。 But you can use a sub-query here as a workaround. 但是您可以在此处使用子查询作为解决方法。 Try something like below... 尝试以下类似的方法...

UPDATE EMPLOYEE 
   SET EMPLOYEE.supervisor_id = (SELECT supervisor_id
                                  FROM (SELECT * FROM EMPLOYEE) EmpFull
                                 WHERE employee_id = '114'),
 WHERE supervisor_id = '114';

Ref here 在这里参考

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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