简体   繁体   中英

How to make two columns unique As a combination?

I have table friends, defined as

UserId int PrimaryKey

OtherUserId int PrimaryKey

Currently, i have the following data

UserId OtherUserId

1 2

I do not want duplicate enteries like

UserId OtherUserId

2 1

how can i implement this using 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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