如何根据其他表的值编写更新

时间:2014-12-09 16:37:34

标签: sql sql-server sql-update

我想更新1个表,但是使用基于其他表的值的条件。总共有三张桌子。

例如

表:电子邮件

   pid | email_addr | code | status |  preferred_ind
   --------------------------------------------------
    0    ex@some.com  HOME    A               Y
    1    ex2@new.com  MB      A               Y 
    2    ex3@new.com  HOME    I               N

表:人

   pid | id | change_ind | 
   -----------------------
   0      53   NULL
   1      54   NULL
   2      55   Y

表:Temp

   id | email_addr
   ---------------
   53   replace1@new.com
   54   replace2@new.com
   55   replace3@new.com

我想

UPDATE email
SET 
    status = 'I'
    preferred_ind = 'N'
WHERE
    email_pid=person_pid and
    person_id = temp_id and
    person_change_ind is NULL and
    email_status_ind = 'A' and
    email_email_addr != temp_email_addr

1 个答案:

答案 0 :(得分:0)

您可以制作子查询

update Email
   set status        = 'I',
       preferred_ind = 'N'
 where Email.pid in (select E.pid
                       from Email E
                      inner join Person P on P.pid = E.pid
                      inner join Temp T on T.id = P.pid
                      where P.change_ind is null
                        and E.status = 'A'
                        and E.email_addr <> T.email_addr);