문제

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:

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 ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top