0

我有两个彼此相同的表,并且t1具有比 更多的数据。我正在使用此查询将丢失的数据从to插入。t2t2t1t2t1

insert into t1
select * from t2
where not exist ( select * from t1
                  where t1.key1 = t2.key1
                  and t1.key2 = t2.key2)

运行此查询时,我得到: ORA-00001 Unique constraint (string.string) 违反错误。

这两个表有key1key2作为键。

由于唯一的约束是两个键,我不明白为什么会出现该错误。

编辑:我现在在“索引”中注意到有 2 个约束都是唯一类型的。

第一个是:key1,random_column 第二个是:key2

带来不便敬请谅解。

4

2 回答 2

1

以防万一对唯一约束有不同的理解,我假设唯一约束是两个字段上的一个唯一索引。如果您对 key1 有唯一约束,对 key2 有唯一约束,那么当 t1 中存在具有相同 t2.key1 值但不同 t2.key2 值的记录时,这将失败,因为添加记录会导致两个t1 中的记录具有相同的 key1 值,这是由 key1 上的唯一约束所禁止的。

如果这是您所拥有的,您需要一个包含两个字段的唯一索引,而不是列约束。

一种可能性是 t2 中的值具有 NULL key1 或 NULL key2。

在表达式中,NULL 输入总是会导致 NULL 结果被认为是错误的。

因此,如果 t2 有一条 key1 为 NULL 且 key2 值为 'value2' 的记录,则 where 子句正在评估

select * from t1
where t1.key1 = NULL and t1.key2 = 'value2'

这不等于

select * from t1
where t1.key1 is NULL and t1.key2 = 'value2'

相反 t1.key1 = NULL 将是不真实的,选择将无法返回结果,exist 将是 false 并且 NOT(exist) 将是 true。但是如果 t1 已经有这样的记录,唯一性约束就会失败。

所以使用这个插入语句。

insert into t1
select * from t2
where not exist ( select * from t1
                  where (t1.key1 = t2.key1 or (t1.key1 is null and t2.key1 is null))
                  and (t1.key2 = t2.key2 or (t1.key2 is null and t2.key2 is null)))
于 2013-03-14T15:18:38.797 回答
0

使用MINUS结果集操作的理想情况

insert into t1
select * from t2
minus
select * from t1
于 2015-03-11T13:05:32.943 回答