[英]SQL Update column values using subquery
In a MySQL database table, I want to UPDATE
some rows with the results from a query.在 MySQL 数据库表中,我想用查询结果
UPDATE
一些行。
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
我只想
UPDATE
出现在以下查询中的行, employeeId
匹配并且newSalary
成为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我原本想将结果加载到临时表中,但我不确定如何获取
SET
值,如此处所示
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.