简体   繁体   English

如何创建sql server数据库列的唯一组合

[英]How to create unique combination of sql server database columns

I'm trying to create relationships table which connects users. 我正在尝试创建连接用户的关系表。

I have the following structure: 我有以下结构:

1. id
2. fromuserid
3. touserid
4. state (none, send, accepted, rejected)

I want to have constraint that any pair from/to should be unique. 我想要约束,来自/的任何一对都应该是唯一的。 I mean there shouldn't be an entry like 我的意思是不应该有像这样的条目

1, **123,124**, send 
2, **124,123**, send

First of all I created constraint that from != to. 首先,我创建了从!=到的约束。 It works perfect: 它非常完美:

CONSTRAINT [CK__FromUserId_ToUserId] CHECK (FromUserId != ToUserId), 

Then I tried to create unique index, constraint etc, nothing helped. 然后我尝试创建唯一索引,约束等,没有任何帮助。

CONSTRAINT [CK_FromUserId_ToUserId_Combination] UNIQUE (FromUserId, ToUserId)

or 要么

CREATE UNIQUE NONCLUSTERED INDEX [IX_FromUserId_ToUserId_Combination] 
  ON USERLINKS (FromUserId, ToUserId)

Both works fine to reject records like: 两者都可以拒绝以下记录:

1, 123,124,send 
2, 123,124,send

But none works to reject records like: 但没有人能拒绝像以下记录:

1, 123,124,send 
2, 124,123,send

Please advise 请指教

You can do this with computed columns. 您可以使用计算列执行此操作。 Add the "leastId" and "greatestId" columns and then create the index on them: 添加“leastId”和“greatId”列,然后在它们上创建索引:

alter table relationships
    add leastId as (case when fromuserid < touserid then fromuserid else touserid end);

alter table relationships
    add greatestId as (case when fromuserid < touserid then touserid else fromuserid end);

create unique index relatinonships_leastId_greastestId_Combination
    on relationships(leastId, greatestId, combination);

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

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