更新两个表中的一列

时间:2014-07-28 20:58:46

标签: sql

我需要将以下语句转换为更新语句,其中我更新1条记录上2个表之间共享的更新列:

select n.updated 
from note n, opportunity_note oo 
where n.NOTE_ID = oo.note_id 
  and oo.opportunity_id = 3525634

我现在必须单独更新两个表,并希望能够只执行一次。

2 个答案:

答案 0 :(得分:0)

更新语句一次只更新一个表,不能一次更新两个或更多。

答案 1 :(得分:0)

我的第一个猜测是你只想要这个(MySQL语法):

update n
    from note n join
         opportunity_note oo 
         on n.NOTE_ID = oo.note_id 
    set n.updated = NEWVALUE
    where oo.opportunity_id = 3525634;

这个通用SQL是:

update note 
   set n.updated = NEWVALUE
   where exists (select 1
                 from opportunity_note oo
                 where note.NOTE_ID = oo.note_id and oo.opportunity_id = 3525634
                );

这适用于任何SQL数据库。

如果要在两个表中有两列要更新,可以在MySQL中执行此操作,但不能在大多数其他数据库中执行此操作。语法很简单:

update n
    from note n join
         opportunity_note oo 
         on n.NOTE_ID = oo.note_id 
    set n.updated = NEWVALUE,
        oo.updated = NEWVALUE
    where oo.opportunity_id = 3525634;

选择n.updated 来自注释n,opportunity_note oo 其中n.NOTE_ID = oo.note_id   和oo.opportunity_id = 3525634