Sql 多列中的唯一索引键
我需要使用SQL Server在表中定义唯一的索引键 例如:Sql 多列中的唯一索引键,sql,sql-server,unique-constraint,unique-index,multiple-columns,Sql,Sql Server,Unique Constraint,Unique Index,Multiple Columns,我需要使用SQL Server在表中定义唯一的索引键 例如: ID Contact1 Contact2 RelationType ------------------------------------------------------------------- 1 1 2 sister // 1 is the 2nd sister 2 3 4 brother
ID Contact1 Contact2 RelationType
-------------------------------------------------------------------
1 1 2 sister // 1 is the 2nd sister
2 3 4 brother // 3 is the 4th brother
3 5 1 father // 5 is the 1st father
4 2 1 sister // bad entry !!!
现在,如何禁止使用唯一索引键在上表中插入错误的数据,如第4个ID?您可以将唯一键与检查约束结合使用,使Contact1中的值更低
create table Relation
(
ID int identity primary key,
Contact1 int not null,
Contact2 int not null,
unique (Contact1, Contact2),
check (Contact1 < Contact2)
)
创建表关系
(
ID int标识主键,
Contact1 int不为空,
Contact2 int不为空,
唯一(联系人1、联系人2),
检查(触点1<触点2)
)
您可以创建一个计算列,其中包含两个数字的字符表示形式(先是较小的一个),然后在计算列上创建唯一约束
case when Contact1 > Contact2 then convert(varchar, Contact2) + convert(varchar, Contact1)
else convert(varchar, Contact1) + convert(varchar, Contact2)
如果5,3已经存在,此解决方案将允许输入5,3,但不允许输入3,5。您正在建模什么逻辑/规则?如果不知道这个问题的答案,就很难确切地知道问题是什么
这就是说,您的表看起来是非规范化的,可能会使应用约束变得复杂。如果您试图简单地强制执行“一个联系人对一个id是唯一的”,则取出“联系人2”列,并在第四个id中的“联系人1”上设置一个唯一的约束。Contact1和Contact2与第一个id类似。确定。contact1和contact2代表什么?是来自另一个表的FK吗?是的,它们来自Contacts表…使用触发器检查条件您的解决方案为真但不是最好的,因为用户填写数据并且(contact1