简体   繁体   English

用于创建表的 SQL 查询具有唯一约束,但该列的数据不唯一

[英]SQL query used to create table has unique constraint, but the data for that column is not unique

create table table1 (
   table_identifier integer identity,
   routing_identifier integer not null,
   account_code char(4) not null),
   constraint pk_table1 primary key (table_identifier),
   constraint ak_table1 unique (routing_identifier, account_code)

I inserted data myself by creating random test data, and the data I have inserted in routing_identifier and account_code have duplicates in them.我通过创建随机测试数据自己插入数据,并且我在routing_identifieraccount_code中插入的数据在其中重复。 I didn't notice until now that both of those columns have many duplicates in the test data I created.直到现在我才注意到这两列在我创建的测试数据中有很多重复项。 I'm not sure why it didn't error out stating unique key, no duplicates allowed or something.我不确定为什么它没有错误地指出唯一密钥,不允许重复或其他东西。 Does anyone know why this is?有人知道为什么吗?

unique (routing_identifier, account_code) means that the combination of routing_identifier and account_code should be unique, not that they are both unique on their own right. unique (routing_identifier, account_code)表示routing_identifieraccount_code的组合应该是唯一的,而不是它们本身都是唯一的。 Eg, consider these three unique pairs: (1, 10), (2, 10) and (1, 20) - each of these pairs is unique, but neither routing_identifier nor account_code are unique on their own right.例如,考虑这三个唯一对:(1, 10)、(2, 10) 和 (1, 20) - 这些对中的每一对都是唯一的,但routing_identifieraccount_code本身都不是唯一的。

If you want each of these columns to be unique, you should define two separate unique constraints:如果您希望这些列中的每一列都是唯一的,您应该定义两个单独的唯一约束:

create table table1 (
   table_identifier integer identity,
   routing_identifier integer not null,
   account_code char(4) not null),
   constraint pk_table1 primary key (table_identifier),
   constraint ak_routing_identifier_table1 unique (routing_identifier), -- Here!
   constraint ak_account_code_table1 unique (account_code) -- And here!
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM