Cameron
Cameron

Reputation: 28783

Unique constraint across two columns

I have a table called friends with the following structure:

id
user_id
friend_id

and I want the rows to be unique so for example:

1, 6, 12
2, 6, 12

would break! I've achieved this with: ALTER TABLE friends ADD UNIQUE INDEX user_id_friend_id (user_id, friend_id);

BUT I also want the following to not be possible

1, 6, 12
2, 12, 6

How do I do that? I tried doing the same statement but with the fields reversed but it didn't work... Any ideas?

Upvotes: 1

Views: 112

Answers (1)

Laurence
Laurence

Reputation: 10976

You could use triggers to ensure that user_id <= friend_id, this with the unique constraint will achieve what you want. You'll need an insert and update trigger like this:

Create Trigger
  Friends_ins_check 
Before Insert On
  Friends
For Each Row
Begin
  If new.user_id > new.friend_id Then
    Set @temp = new.user_id;
    Set new.user_id = new.friend_id;
    Set new.friend_id = @temp;
  End If;
End

Example

Upvotes: 2

Related Questions