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 (eg "1,5,18,9")
posts
table:
posts
.id posts
.userid comments
table:
comments
.id comments
.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, but 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, ie - WHERE p.userid IN (1,5,18,9).
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.