简体   繁体   English

如何使两个列成为唯一的组合?

[英]How to make two columns unique As a combination?

I have table friends, defined as 我有桌友,定义为

UserId int PrimaryKey UserId int PrimaryKey

OtherUserId int PrimaryKey OtherUserId int PrimaryKey

Currently, i have the following data 目前,我有以下数据

UserId OtherUserId UserId OtherUserId

1 2 1 2

I do not want duplicate enteries like 我不想像

UserId OtherUserId UserId OtherUserId

2 1 2 1

how can i implement this using SQL Server? 我如何使用SQL Server来实现呢?

You can do this by adding a computed column and then a unique index: 您可以通过添加计算列和唯一索引来做到这一点:

alter table friends UserId_least as (case when UserId < OtherUserId then UserId else OtherUserId end);

alter table friends UserId_greatest as (case when UserId < OtherUserId then OtherUserId else UserId end);

create unique index unq_friends_least_greatest
    on friends(UserId_least, UserId_greatest);

Your question is a little broad. 您的问题有点广泛。 Please be advised that you can only have one primary key per table since it serves as the identification. 请注意,每个表只能用作一个主键,因为它用作标识。 As for the data, you could try to use auto increment and not null to avoid duplicate answers. 至于数据,您可以尝试使用自动递增而不是null以避免重复的答案。

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

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