Get latest 3 comments for a list of posts
Currently I'm running one query to get all posts for a user, then in the loop for that, I am querying for the latest 3 comments for that particular post. Super inefficient; I'm querying over and over again for every post.
I would like to consolidate my queries so that I query just once for all posts, and just once for all comments for those particular posts. At the moment I have a comma-separated list that I made for all posts for this user (e.g. "1,5,18,9")posts
table:
posts
.idposts
.userid
comments
table:
comments
.idcomments
.relid (this is the postid)comments
.userid
The query should use the $posts_list I have, which is the comma-separated list of posts. Or a subselect for all posts for this user, bu开发者_开发知识库t that seems inefficient since I already have the post list in a string.
Thanks so much for any help!
Try this query -
SELECT p.id, p.userid, c.id, c.userid
FROM posts p
JOIN (
SELECT c1.*, COUNT(*) rank FROM comments c1
LEFT JOIN comments c2
ON c2.relid = c1.relid AND c2.id <= c1.id
GROUP BY c1.relid, c1.id
) c
ON p.id = c.relid
WHERE rank < 4
And add condition you need, i.e. - WHERE p.userid IN (1,5,18,9).
精彩评论