Skip to content
Advertisement

How to avoid MySQL composite primary key permutations?

There’s this mutual friendship relation where (friend_A, friend_B) is the same as (friend_B, friend_A).

I’ve tried adding a unique key, but it was to no avail:

Is there a way to avoid these permutations ?

Advertisement

Answer

You can do:

Then if it won’t accept symmetric rows:

See running example at db<>fiddle.

There’s also another trick. What you can alternatively do is to enforce buddy_id < mate_id. This, however, will restrict the way you insert data. For example you can do:

Then, when you insert:

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement