Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing Friends in Database for Social Network

For storing friends relationships in social networks, is it better to have another table with columns relationship_id, user1_id, user2_id, time_created, pending or should the confirmed friend's user_id be seralized/imploded into a single long string and stored along side with the other user details like user_id, name, dateofbirth, address and limit to like only 5000 friends similar to facebook?

Are there any better methods? The first method will create a huge table! The second one has one column with really long string...

On the profile page of each user, all his friends need to be retrieved from database to show like 30 friends similar to facebook, so i think the first method of using a seperate table will cause a huge amount of database queries?

like image 250
Nyxynyxx Avatar asked Jul 08 '11 00:07

Nyxynyxx


People also ask

Which type of database would you use for storing friendship networks?

Graph databases work by storing the relationships along with the data. Because related nodes are physically linked in the database, accessing those relationships is as immediate as accessing the data itself.

How does Facebook store friends list in database?

Each user is sharded on to a single User Database (UDB). Each UDB has a "friends" table with columns id1, id2 where id1 is the primary key. id1 is always a user that is on that UDB, while id2 is the foreign user. To get all of a user's friends, you SELECT * from friends where id1=<id> from their UDB.

What type of database is used by Facebook?

At Facebook we use MySQL to manage many petabytes of data, along with the InnoDB storage engine that serves social activities such as likes, comments, and shares.


1 Answers

The most proper way to do this would be to have the table of Members (obviously), and a second table of Friend relationships.

You should never ever store foreign keys in a string like that. What's the point? You can't join on them, sort on them, group on them, or any other things that justify having a relational database in the first place.

If we assume that the Member table looks like this:

MemberID int Primary Key
Name varchar(100) Not null
--etc

Then your Friendship table should look like this:

Member1ID int Foreign Key -> Member.MemberID
Member2ID int Foreign Key -> Member.MemberID
Created datetime Not Null
--etc

Then, you can join the tables together to pull a list of friends

SELECT m.*
FROM Member m
RIGHT JOIN Friendship f ON f.Member2ID = m.MemberID
WHERE f.MemberID = @MemberID

(This is specifically SQL Server syntax, but I think it's pretty close to MySQL. The @MemberID is a parameter)

This is always going to be faster than splitting a string and making 30 extra SQL queries to pull the relevant data.

like image 198
Mike Caron Avatar answered Oct 17 '22 14:10

Mike Caron