简体   繁体   English

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

[英]Update ONE record per condition in a table

I looked into this thread, and I thought I'd find my answers there, but unfortunately didn't ... 我调查了这个主题,我以为可以在这里找到答案,但是不幸的是没有...

UPDATE statement in Oracle using SQL or PL/SQL to update first duplicate row ONLY Oracle中使用SQL或PL / SQL的UPDATE语句仅更新第一个重复行

If our customers don't have a default email address selected I need to update that value. 如果我们的客户未选择默认电子邮件地址,则需要更新该值。

The following statement updates ALL records of that table if the customer does not have a default email yet: 如果客户还没有默认电子邮件,则以下语句更新该表的所有记录:

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')

But if a customer happens to have more than one entry in the si_contactemails table I only need the first record for this customer updated, can only have one default. 但是,如果一个客户恰好在si_contactemails表中有多个条目,那么我只需要更新该客户的第一条记录,就只能有一个默认值。

I tried with the following addition which I found in the article mentioned above, but it only updates the first record for which all conditions are true - how can I update all records for which the conditions are true? 我尝试了在上面提到的文章中找到的以下添加项,但它仅更新了所有条件都为真的第一条记录-如何更新条件为真的所有记录?

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'))

Any input appreciated :-) 任何输入表示赞赏:-)

Thanks a lot, 非常感谢,

Steph 史蒂芬

Here's one approach: 这是一种方法:

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
        )
;

It finds exactly one rowid in si_contactemails for each customer that (1) has status A and is not deleted and (2) has no default record in si_contactemails . 它为si_contactemails中的每个客户准确找到一个rowid ,该(1)状态为A且未删除,并且(2) si_contactemails没有默认记录。 It then updates every record in that set of rowid s. 然后,它更新该rowid集中的每个记录。

(Disclaimer: not tested.) (免责声明:未经测试。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM