In a MySQL database table, I want to UPDATE
some rows with the results from a query.
For instance, I have a table
TABLE employees(
employeeId int,
salary int,
)
and I want to UPDATE
only the rows that appear in the below query, with employeeId
s matching and with newSalary
becoming the modified value for salary
(SELECT employeeId, newSalary FROM ....)
I originally thought to load the results into a temporary table, but I'm not sure how to get the SET
value, as illustrated here
UPDATE employees
SET salary = (???)
WHERE employeeId exists in tempTable
You might comment that this results in denormalization, I'm aware of this. I suspect there will be some "you don't want to do this" type responses, for the sake of brevity, please just assume I have a good reason.
Join the subquery and your table you gonna updating:
UPDATE employees x INNER JOIN (
SELECT employeeId, newSalary FROM ....
) y ON x.employeeId=y.employeeId
SET x.salary=y.newSalary
update employees, tempTable
set employees.salary=tempTable.newSalary
wnere employees.employeeId=tempTable.employeeId;
update employees
inner join temptable
on employees.employeeid = temptable.employeeid
set employees.salary = temptable.newsalary
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.