Storing Friends in Database for Social Network
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 KeyName varchar(100) Not null--etc
Then your Friendship table should look like this:
Member1ID int Foreign Key -> Member.MemberIDMember2ID int Foreign Key -> Member.MemberIDCreated datetime Not Null--etc
Then, you can join the tables together to pull a list of friends
SELECT m.*FROM Member mRIGHT JOIN Friendship f ON f.Member2ID = m.MemberIDWHERE 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.
Separate table as in method 1. method 2 is bad because you would have to unserialize it each time and wont be able to do JOINS on it; plus UPDATE's will be a nightmare if a user changes his name, email or other properties.
sure the table will be huge, but you can index it on Member11_id, set the foreign key back to your user table and could have static row sizes and maybe even limit the amount of friends a single user can have. I think it wont be an issue with mysql if you do it right; even if you hit a few million rows in your relationship table.