更新表中每个条件的一条记录

时间:2012-07-23 16:58:54

标签: sql oracle

我调查了这个帖子,我以为我会在那里找到答案,但遗憾的是没有......

UPDATE statement in Oracle using SQL or PL/SQL to update first duplicate row ONLY

如果我们的客户没有选择默认电子邮件地址,我需要更新该值。

如果客户还没有默认电子邮件,则以下语句会更新该表的所有记录:

update si_contactemails 
set ISDEFAULT = 'Y'
where entityid in
(select customerid from si_customers where custstatus = 'A' and deleted = 0)
and entityid in (select entityid from si_contactemails group by entityid having MAX(ISDEFAULT) = 'N')

但是如果客户恰好在si_contactemails表中有多个条目,我只需要更新此客户的第一条记录,只能有一条默认值。

我尝试了上面提到的文章中添加的以下内容,但它只更新了所有条件都为真的第一条记录 - 如何更新条件为真的所有记录?

update si_contactemails 
set ISDEFAULT = 'Y'
where entityid in
(select customerid from si_customers where custstatus = 'A' and deleted = 0)
and entityid in (select entityid from si_contactemails group by entityid having MAX(ISDEFAULT) = 'N')
AND rowid = (SELECT min(rowid) 
                 FROM   si_contactemails 
                 WHERE entityid in (select min(entityid) from si_contactemails group by entityid having MAX(ISDEFAULT) = 'N'))

任何意见: - )

非常感谢,

斯蒂芬

1 个答案:

答案 0 :(得分:0)

这是一种方法:

UPDATE si_contactemails
   SET isdefault = 'Y'
 WHERE rowid IN
        ( SELECT MIN(rowid)
            FROM si_contactemails
           WHERE entityid IN
                  ( SELECT customerid
                      FROM si_customers
                     WHERE custstatus = 'A'
                       AND deleted = 0
                    MINUS
                    SELECT entityid
                      FROM si_contactemails
                     WHERE isdefault = 'Y'
                  )
           GROUP
              BY entityid
        )
;

它在rowid中为每个客户找到一个si_contactemails,其中(1)状态为A且未删除,(2)si_contactemails中没有默认记录。然后它会更新该组rowid s。

中的每条记录

(免责声明:未经测试。)