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

时间:2014-10-23 06:32:03

标签: mysql sql

table A
    uid
    uname

temp table B
    uid
    uname

表B不是真正的表,而是子查询的结果,如

select uid, uname
from tableC left join tableD on tableC.pid = tableD.pid
where tableC.qid = tableD.qid
group by uid;

我想更新A.uname = B.uname,其中A.uid = B.uid

我怎么能用MySQL做到这一点?

2 个答案:

答案 0 :(得分:2)

将子查询视为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

另请注意,在LEFT JOIN中,引用第二个表的所有条件都应位于ON子句中。否则,您将过滤掉所有不匹配的行,因为这些列的值将为NULL,这将取消使用LEFT JOIN而非INNER JOIN的点。

答案 1 :(得分:0)

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