简体   繁体   中英

php mysql show friends' posts

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM