snippetMinor
How to prevent redundant relationships in data?
Viewed 0 times
preventredundanthowrelationshipsdata
Problem
If I want to link users with other users. Would this be a good way to do it:
I'm asking because I probably get double data like this if i don't do specific checks:
I'm asking because I probably get double data like this if i don't do specific checks:
+------+-------------+
|userId|relatedUserId|
+------+-------------+
| 1 | 2 |
| 1 | 3 |
| 2 | 1 |
| 2 | 3 |
| 3 | 1 |
| 3 | 2 |
+------+-------------+Solution
It sounds like you are describing a mutual relationship such that there is no difference between
(1,2) and (2,1). In this case you should design your code to always insert the lower userId as the first value and the higher as the second. Then you can use AlexKuznetsov's suggestion and add a CHECK constraint of `(userId to < because the lower number being first makes more sense to me. It works either way and may make more sense the other way in your environment.Context
StackExchange Database Administrators Q#15928, answer score: 4
Revisions (0)
No revisions yet.