简体   繁体   English

如何在MySQL更新查询中将子选择结果用作临时表?

[英]How to use subselection result as temp table in MySQL update query?

table A
    uid
    uname

temp table B
    uid
    uname

table B is not a real table but a result of subquery like 表B不是真正的表,而是子查询的结果,例如

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 我想更新集合A.uname = B.uname,其中A.uid = B.uid

how can I do that with MySQL? 我该如何使用MySQL?

Treat the subquery as a table in a JOIN : 将子查询视为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. 另外,请注意,在LEFT JOIN ,引用第二个表的所有条件都应在ON子句中。 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 . 否则,您将过滤掉所有不匹配的行,因为这些列的值将为NULL ,这将否定使用LEFT JOIN而不是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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM