多列唯一索引键
问题描述:
我需要使用SQL Server在我的表中定义唯一索引键。多列唯一索引键
例如:
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 !!!
现在,我怎样才能禁止插入错误数据像上表中使用唯一索引键的第四ID?
答
你可以创建一个包含两个数字的字符表示计算列(较小的一个第一)联合创建,然后在计算列上的唯一约束。
case when Contact1 > Contact2 then convert(varchar, Contact2) + convert(varchar, Contact1)
else convert(varchar, Contact1) + convert(varchar, Contact2)
该解决方案将允许输入5,3而不是3,5如果5,3已经存在。
答
您可以将一个唯一键与检查约束结合使用,使您在Contact1中具有较低的值。
create table Relation
(
ID int identity primary key,
Contact1 int not null,
Contact2 int not null,
unique (Contact1, Contact2),
check (Contact1 < Contact2)
)
+0
你的解决方案是真实的,但不是最好的,因为用户填写数据和(contact1
+0
在将行插入表格之前,可以由代码负责您的操作。没有必要用此来打扰用户。 –
答
您建模的逻辑/规则是什么?在不知道这个问题的答案的情况下,很难确切地知道问题所在。
这就是说,它看起来像你的表非规范化,并可能使应用程序约束复杂。如果您试图简单地强制执行“某个联系人对某个ID唯一”,那么请取出联系人2栏并在联系人1上添加一个唯一约束。
为什么第四个条目不好? –
第四个ID Contact1和Contact2类似于第一个ID。 – Nildarar
好的。 contact1和contact2代表什么? –