mysqlsqldatabasefacebooksocial-networking

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?


Solution

  • 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.