JasonDavis JasonDavis - 1 year ago 137
MySQL Question

Friend of a friend in PHP/MySQL?

I have a social network similar to myspace/facebook. In my code you are either a person's friend or not a friend, so I show all actions from people you are friends with (in this post I will refer to actions as bulletin posts alone to make it easier to visualize.

So you every time a person post a bulletin it will show up to any person who is there friend.

In mysql you would get a persons friend list by doing something like this,

SELECT user_id FROM friends WHERE friend_id = 1 (user ID)

I want to know how a site like facebook and some others would show all bulletin post from your friends and from your friends' friends?

If anyone has an idea please show some code like what kind of mysql query?

Answer Source

The answer is that they aren't doing selects on a friend table, they are most likely using a de-normalized news-event table. We implemented a news-feed similar to Facebooks on DoInk.com, here's how we did it:

There is the notion of a "NewsEvent" it has a type, an initiator (a user id) and a target user (also a user id). (You can also have additional column(s) for other properties relevant to the event, or join them in)

When a user posts something on another users wall we generate an event like this:

INSERT INTO events VALUES (wall_post_event, user1, user1)

When viewing user1's profile, you'd select for all events where user1 is either the initiator or the target. That is how you display the profile feed. (You can get fancy and filter out events depending on your privacy model. You may consider doing this in memory for performance reasons)


SELECT * FROM events WHERE initiator = user1 or target = user1 //to see their profile feed

SELECT * FROM events WHERE initiator IN (your set of friend ids) //to see your newsfeed

When you want to see the newsfeed for all events relative to your friends you might do a query selecting for all events where the initiator is in your set of friends.

Avoid implementations with sub-selects, depending on the complexity, they will not scale.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download