What is the best way to show friends’ posts?
Each user can have maximum 5000 friends.
Steps:
1) mysql retrieve 5000 friends’ usernames.
2) store 5000 friends’ usernames in a php array.
3) SELECT posts, datatime FROM tbl_posts WHERE username IN ($array) ORDER BY id DESC LIMIT 10;
Question : Let’s say zac1987 is 5000th item in php array. If the 10 latest posts are posted by zac1987, does mysql need to waste times to loop through 5000 items to determine whether or not the post is posted by him? So if I want to show 10 latest posts, does mysql need to loop through 5000 friends x 10 posts = 50,000 items? And every 5 seconds need to check if there is any new posts, so it means every 5 seconds need to loop 50,000 items? Is there any method to prevent so many looping/filtering items process?
You should create indexes on
post (post_date),post (author),friend (friend_id, user_id)Depending on the cardinality,
MySQLwill either makepostleading in the join (in which case the first index will be used) or makefriendleading (in which case it will gather all friends’ posts and sort them).