Many people say that I should create a friendships table(userid , friendid).
My question is:
Won't there be a double record for every friendship ? like:
12 is friend with 5
+
5 is friend with 12
Is there a way to prevent this ?
| OR |
Should I just ignore that ?
There are at least two approaches you could use:
userid
is always less than the friendid
.The second approach costs twice as much storage and is redundant but it does mean that some queries can be much simpler and will perform better. For example, consider fetching all the common friends of user 'a' and 'b' with each of the approaches:
Approach 1:
SELECT friendid
FROM
(
SELECT friendid FROM friendships WHERE userid = 'a'
UNION
SELECT userid FROM friendships WHERE friendid = 'a'
) T1
JOIN
(
SELECT friendid FROM friendships WHERE userid = 'b'
UNION
SELECT userid FROM friendships WHERE friendid = 'b'
) T2
ON T1.friendid = T2.friendid
Approach 2:
SELECT T1.friendid
FROM friendships T1
JOIN friendships T2
ON T2.userid = 'b' AND T1.friendid = T2.friendid
WHERE T1.userid = 'a'
I would ask: Is it possible for someone to be friends with themselves? What does 'friendship' mean - is it bidirectional or unidirectional. If bidirectional then one record will do, right? If unidirectional, then two records are needed. If someone cannot be friends with themselves, then you implement a business rule in the data entryu page (liek in a web page this would be good for javascript) where friend1 id <> friend2 id Not sure I agree with 'less than' - they just can't be equal
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With