【问题标题】:ORA-00001 Unique constraint (string.string) violatedORA-00001 违反唯一约束 (string.string)
【发布时间】:2013-03-14 15:09:15
【问题描述】:

我有两个完全相同的表t1 和t2,但t2 的数据比t1 多。 我正在使用此查询将缺失的数据从t2 插入到t1。

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) 违反错误。

这两个表有key1 和key2 作为键。

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

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

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

很抱歉给您带来不便。

【问题讨论】:

  • 唯一约束在哪一列?
  • 它击中错误的键之一。我试图只使用错误消息弹出的 where 语句之一。但我得到了同样的错误信息。

标签: sql oracle plsqldeveloper


【解决方案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)))

【讨论】:

  • 如果要检查是否相等且NULL值是否相等,可以使用WHERE DECODE(t1.key1, t2.key1, 1) = 1代替WHERE t1.key1 = t2.key1。
【解决方案2】:

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

insert into t1
select * from t2
minus
select * from t1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-11-06
    • 2016-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多