简体   繁体   中英

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. 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

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 . 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 . 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

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