There is a table of posts and comments . It is necessary (one select) to select posts and 3 comments to each post.
SELECT p.id, p.userID, p.title, GROUP_CONCAT(c.id, c.text) LEFT JOIN comments c FORCE INDEX(IDX_comments_postID) ON p.id = c.postID; GROUP BY p.id; This select returns everything you need, but the number of comments should be <= 3 for each post. How can this be organized?
UPDATE: Sergey Moiseenko issued what is needed, the finished version is as follows:
SELECT p.id, p.userID, p.title, GROUP_CONCAT(c.id) FROM posts p LEFT JOIN -- тут магия (SELECT IF(c.postID = @i, @n := @n + 1, @n := 1) AS a, @i := c.postID AS postID, c.id, c.text FROM (SELECT * FROM comments c ORDER BY c.id DESC) c, (SELECT @n := 0, @i := 0) x ORDER BY c.postID ASC) c ON p.id = c.postID WHERE a <= 3 OR a IS NULL GROUP BY p.id;
posts(if there are several comments), I remove them by grouping .... GROUP_CONCAT grouped entries (comments) give what is wrong in this? The question is how to limit their number - Max32NovHAVING COUNT(c.id) <= 3possible - Alexey Shimansky