SQL:如果缺少值,则使用同一个表中的替代值更新表

时间:2016-11-29 15:51:04

标签: sql

我有一个数据表,如下所示:

-------------------------------------------------------
member id | Email_address | alternate_Email_Address 
------------------------------------------------------
001       | ss@gmail.com  | ss@hotmail.com
001       |               | ss@hotmail.com
001       |               | ss@hotmail.com
002       | aa@gmail.com  | aa@gmail.com
002       |               | aa@gmail.com

我想运行一个SQL,它将复制所有alternate_Email_Address相同的所有地址的电子邮件地址。

运行SQL后,我希望表格如下:

-------------------------------------------------------
member id | Email_address | alternate_Email_Address 
------------------------------------------------------
001       | ss@gmail.com  | ss@hotmail.com
001       | ss@gmail.com  | ss@hotmail.com
001       | ss@gmail.com  | ss@hotmail.com
002       | aa@gmail.com  | aa@xyz.com
002       | ss@gmail.com  | aa@xyz.com 

2 个答案:

答案 0 :(得分:2)

如果我理解你想要的东西,那么使用ANSI标准SQL的方法是:

update t
    set email_address = (select max(t2.email_address)
                         from t t2
                         where t2.alternate_Email_Address = t.alternate_Email_Address and
                               t2.email_address is not null
                        )
    where email_address is null;

答案 1 :(得分:0)

UPDATE <TABLE> 
SET    email_address = 
       (SELECT email_address 
        FROM   <TABLE> lu 
        WHERE  lu.alternate_email_address = <TABLE>.alternate_email_address 
               AND (email_address IS NOT NULL AND length(lu.email_address) > 1) limit 1) 
WHERE  email_address IS NULL

如果它是空字符串,则用WHERE email_address = ""替换where,而不是NULL。

确保您在alternate_email_address上有索引。出于性能原因,如果可能,请使用limit 1而不是聚合函数。