Oracle更新表中的重复行
本文关键字:更新 Oracle | 更新日期: 2023-09-27 18:23:42
我有一个名为users的Oracle表,其列为
name, location, organization, valid_from, valid_to, active.
我想做的是:如果有两条记录具有相同的名称、位置、组织,但valid_to、valid_from间隔重叠,则将每条记录的活动状态设置为"NOK"。以下是我尝试的方法:
UPDATE table SET active= 'NOK'
WHERE
(name, location, organization) IN (
SELECT t1.name, t1.location, t1.organization
FROM table t1
WHERE (valid_from > t1.valid_from and valid_to < t1.valid_to )
GROUP BY t1.name, t1.location, t1.organization
HAVING COUNT(*) > 1) ;
但这似乎并没有达到我的愿望。我做错了什么?
子查询中的WHERE子句对于所有行都将为FALSE,因为您没有为某些列指定表别名:
(valid_from > t1.valid_from and valid_to < t1.valid_to )
将被假定为
(t1.valid_from > t1.valid_from and t1.valid_to < t1.valid_to )
我认为这是你想要的:
UPDATE table t1 SET active = 'NOK'
WHERE EXISTS
( SELECT 1
FROM table t2
WHERE t2.name = t1.name
AND t2.location = t1.location
AND t2.organization = t1.organization
AND t1.valid_from <= t2.valid_to
AND t2.valid_from <= t1.valid_to
AND t1.ROWID != t2.ROWID
);
但是,如果valid_from或valid_to可以为null,那么您也需要处理这种情况。
(ROWID比较是为了防止拖带与自身匹配!)
试试这个方法:
UPDATE table SET a.active= 'NOK'
from table a
inner join (
SELECT t1.name, t1.location, t1.organization
FROM table t1
WHERE (valid_from > t1.valid_from and valid_to < t1.valid_to )
GROUP BY t1.name, t1.location, t1.organization
HAVING COUNT(*) > 1) b
on a.name = b.name and a.location = b.location and a.organization = b.organization;