I have a table call EMPLOYEE, which contains supervisor_id and employee_id. I am trying to update one of the employee(114) supervisor (100), to become the supervisor for 114 employees.
Employee_id | Supervisor_id |
---|---|
114 | 100 |
115 | 114 |
116 | 114 |
117 | 114 |
118 | 114 |
119 | 114 |
I tried using this update statement:
UPDATE EMPLOYEE AS E1
JOIN (SELECT employee_id
FROM EMPLOYEE
WHERE supervisor_id = 114) AS E2
SET E1.supervisor_id = E2.employee_id
WHERE E1.supervisor_id = 114;
But it printed 115 as the supervisor_id, when it was supposed to print 110. Is there anything wrong with the statement?
Note: I can only use update statement only.
What I feel is that your join operation is giving some different output, can you try to join on table entry like below:
UPDATE EMPLOYEE AS E1
JOIN (SELECT *
FROM EMPLOYEE
WHERE supervisor_id = 114) AS E2
SET E1.supervisor_id = E2.employee_id
WHERE E1.supervisor_id = 114;
A suggestion, before executing an update
with inner join
try the same query using select
statement to view the rows returned. In your case you can't use update
with join
because the condition supervisor_id = 114
will remove the value of supervisor_id=100
.
You should use subquery ,but in update
or delete
you cant specify the same table , so you should wrap the subquery into an outer query giving the table an alias.
This nested query is not very good for performance.
Try:
update employee set supervisor_id= ( select t.supervisor_id
from ( SELECT supervisor_id
FROM employee
WHERE employee_id = 114
) as t
)
where supervisor_id=114;
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.