Reputation: 1275
I am trying to do a following/follower type of concept that many social networks have. I have 2 INT fields called me and following, Those INT fields are composed of users Unique ID. I want to make so that if user 23 is following user 7 or 23->7 then user 23 can not follow user 7 again because the relationship already exists. This picture will clear things up
Notice above the first 2 rows are 31->27 or user 31 is following 27 twice that is redundant. Is there some constraint that I can use to prevent that from happening ? I am using postgres version 9.4
Upvotes: 1
Views: 27
Reputation: 1269563
You can do this by creating a unique index. But not just any unique index, one on expressions:
create unique index unq_t_me_following
on (least(me, following), greatest(me, following));
Upvotes: 1