MySQL UPDATE SET字段等于SELECT

时间:2012-12-21 22:47:36

标签: mysql insert-update

我正在尝试使用电子邮件地址更新多行。 T1.email将根据T2.name中存在的T1.name更新T2.email。

目前,查询看起来像这样。

UPDATE T1
SET T1.email = T2.email
FROM Table1 T1
INNER JOIN Table2 T2 ON T1.name = T2.name
WHERE T1.name = T2.name
AND (Some conditions)
LIMIT 1398

这里提出了一个类似的问题,但是给出了语法错误。 SQL UPDATE SET one column to be equal to a value in a related table referenced by a different column?

我也尝试使用ANY进行更新。

UPDATE Table1
SET Table1.email = ANY
    (
        SELECT Table2.email FROM Table2 
        WHERE Table1.accountid = 901234 
        AND Table2.pid = 123 
        AND Table2.email IS NOT NULL 
    )

WHERE Table1.name IN
    (
        SELECT Table2.name FROM Table2
        WHERE Table1.accountid = 19574
        AND Table2.pid = 123 
        AND Table2.email IS NOT NULL
    ) 

LIMIT 1398

目前,这会返回错误“SQL Error(1242):Subquery返回多于1行”。

可能是复制和粘贴工作的开始!

1 个答案:

答案 0 :(得分:1)

详见UPDATE Syntax,对于你想要的MySQL:

UPDATE Table1 T1 JOIN Table2 T2 USING (name)
SET    T1.email = T2.email
WHERE  (Some conditions)
LIMIT  1398