Sql 仅在不违反唯一约束的情况下更新表
我有下表:Sql 仅在不违反唯一约束的情况下更新表,sql,database,oracle,Sql,Database,Oracle,我有下表: Id Account_Number Csd_id pk_id dk_id 1 343 200 100 50 2 234 400 200 70 3 343 400 100 70 我对账号、csd\u id和pk\u id有唯一的限制 现在,我想将所有csd\u id更新为200,其中csd\u id是400,仅在不违反上述唯一约束
Id Account_Number Csd_id pk_id dk_id
1 343 200 100 50
2 234 400 200 70
3 343 400 100 70
我对账号
、csd\u id
和pk\u id
有唯一的限制
现在,我想将所有csd\u id
更新为200
,其中csd\u id
是400
,仅在不违反上述唯一约束的情况下
更新完成后,我必须删除
csd\u id
为400
的剩余记录,您只需要一个update
语句,其中包含not exists
子句,以避免违反约束的更新。当然,对于剩余的行,还需要一个简单的delete
语句:
update tbl t1
set t1.csd_id = 200
where t1.csd_id = 400
and not exists (
select null
from tbl t2
where t2.account_number = t1.account_number
and t2.pk_id = t1.pk_id
and t2.csd_id = 200
);
delete tbl where csd_id = 400;
编辑
不太可能,但如果账号
或主键id
可能为空:
update tbl t1
set t1.csd_id = 200
where t1.csd_id = 400
and not exists (
select null
from tbl t2
where (t2.account_number = t1.account_number or (t2.account_number is null and t1.account_number is null))
and (t2.pk_id = t1.pk_id or (t2.pk_id is null and t1.pk_id is null))
and t2.csd_id = 200
);
delete tbl where csd_id = 400;
如果对这三列有唯一的约束,那么如何在表中保存数据?约束已经被违反了(Oracle不允许您这样做),因此您所说的某些内容实际上是不真实的。请澄清。唯一的限制是这三者的结合,而不是个人。是的,完全正确。最后两行在所有三列中的值都完全相同。我已经编辑了它,这只是虚拟数据。在实际的表中,记录数超过1000条。第一步是编写一个select查询,找出符合此规则的行。对于初学者来说,应该是从csd_id=200的表中选择*,
SELECT*,如果account_number
和/或pk_id
中有空值,这会起作用吗?看看这些评论,我知道我在你发布这个答案前的三个小时问过OP专栏是否可以为空;我仍然没有看到OP的回应。我也没有看到你的答案中提到的空值。@ MathFee:我为可完成性添加了可空的场景,但我认为这是一个非常不可能的边缘情况。在我看来,在多列唯一约束中处理空值的方式使得它们不适合通用。