1

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?

2
  • What database are you using? Sometimes this is easy, sometimes it's not. Depends on the database. Commented Dec 16, 2012 at 22:56
  • I have the constraint in the code for my app. But I'd like to do it in the DB as well. Take it MySQL is rubbish for this? Commented Dec 16, 2012 at 22:58

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

if someone is confused by For Each Row like i was, here is a post clarifying the behaviour: stackoverflow.com/questions/23374151/…?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.