Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Update column values using subquery

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

like image 499
Mike Avatar asked Aug 15 '11 12:08

Mike


3 Answers

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
like image 63
rabudde Avatar answered Oct 05 '22 16:10

rabudde


update employees, tempTable
set employees.salary=tempTable.newSalary
wnere employees.employeeId=tempTable.employeeId;
like image 27
ajreal Avatar answered Oct 05 '22 16:10

ajreal


update employees
inner join temptable
on employees.employeeid = temptable.employeeid
set employees.salary = temptable.newsalary
like image 40
Derek Kromm Avatar answered Oct 05 '22 17:10

Derek Kromm