table A
uid
uname
temp table B
uid
uname
table B is not a real table but a result of subquery like
select uid, uname
from tableC left join tableD on tableC.pid = tableD.pid
where tableC.qid = tableD.qid
group by uid;
I want to update set A.uname = B.uname where A.uid = B.uid
how can I do that with MySQL?
Treat the subquery as a table in a JOIN
:
UPDATE tableA AS a
JOIN (select uid, uname
from tableC
left join tableD on tableC.pid = tableD.pid and tableC.qid = tableD.qid
group by uid) AS b ON a.uid = b.uid
SET a.uname = b.uname
Also, note that in a LEFT JOIN
, all the conditions that refer to the second table should be in the ON
clause. Otherwise, you'll filter out all the non-matching rows, because the values of those columns will be NULL
, and that will negate the point of using LEFT JOIN
rather than INNER JOIN
.
update a
set uname = B.name
from A a
inner join (
select uname [name]
from tableC left join tableD on tableC.pid = tableD.pid
where tableC.qid = tableD.qid
group by uid ) b
ON a.uid = b.uid
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.