【发布时间】:2021-07-22 20:43:31
【问题描述】:
如果给定条件为真,有没有办法忽略唯一约束?
例如,我的数据库中有 3 列形成唯一约束:
create table example_table
(
column_primarykey RAW(16) default NULL not null,
column_a number(8) not null,
column_b number(8) not null,
column_c number(8) not null,
constraint constraint_1
unique(column_a, column_b, column_c)
constraint constraint_2
primary key (column_primarykey)
现在我添加第四列:
alter table example_table
add column_d number(8) not null,
我想要实现的是,如果 column_d 的值已经存在于表中,则唯一约束将被忽略。如果 column_d 在表中不是唯一的,则唯一约束将被忽略,您可以将该行添加到表中。例如这是我表中的现有数据(忽略不相关的主键原因):
| column_a | column_a | column_c | column_d |
|---|---|---|---|
| 1 | 2 | 3 | 1 |
| 3 | 4 | 5 | 2 |
所以我想要的是您可以添加例如 (1, 2, 3, 1) 但不能添加 (1, 2, 3, 2),因为前三个值已经存在一行。只有当 column_d 中的值已经存在并且其他值等于现有行时才可能。
更多帮助理解的例子:
| Example insert | result | reason |
|---|---|---|
| (1, 2, 3, 1) | accepted | d is not unique and a, b, c got same values as the existing row with value 1 for column_d |
| (1, 2, 3, 4) | rejected | a, b ,c exists already in the table |
| (5,6,7,1) | rejected | 1 exists but with different values for a b and c |
| (3,4,5, 2) | accepted | d exists and a, b, c, have the same values |
| (7,8,9,3) | accepted | a, b, c are unique and d does not exist |
【问题讨论】:
-
您使用的是哪个数据库?例如,Oracle 和 SQL Server 将具有不同的语法和功能。我还认为您需要更多地扩展您的示例。显示需要拒绝插入的大量情况,以及应接受插入的大量情况。然后,可能的解决方案将涉及 CHECK 约束而不是 UNIQUE 约束:docs.microsoft.com/en-us/sql/relational-databases/tables/…(取决于您使用的数据库)
-
不清楚为什么(1,2,3,2)不能加?
column_d的值 2 已存在于表中。 -
我正在使用 Oracle。 @Serg (1, 2, 3, 2) 无法添加,因为 (1, 2, 3, 1) 已经在数据库中。如果 column_d 的值相等,则其他值也必须相等。我知道这没有意义,但在我的实际数据库中,我有更多列。我为我的问题简化了它,因为这些是相关的。但是很好,我忘了提到这一点,也许我自己也搞糊涂了。
-
第二个@MatBailie 评论,更多示例可能会有所帮助。
-
转述;如果...任何行已经存在具有相同 (a,b,c) 和不同 (d) 的情况,则插入必须被拒绝?
标签: sql oracle constraints unique-constraint