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?
SELECT p.*
FROM friend f
JOIN post p
ON p.author = f.friend_id
WHERE f.user_id = $myuserid
ORDER BY
p.post_date DESC
LIMIT 10
You should create indexes on post (post_date)
, post (author)
, friend (friend_id, user_id)
Depending on the cardinality, MySQL
will either make post
leading in the join (in which case the first index will be used) or make friend
leading (in which case it will gather all friends' posts and sort them).
精彩评论