I would like to get a list of Posts including the last 2 comments for each particular post (if any). I have been using the query below, that returns all the comments for each post, however it has a limitation, because the GROUP_CONCAT() length is limited to 1024 characters by default, so if there are a lot of comments on a post, the 'comments' value will be cut off, and it won't be a valid JSON output anymore.
SELECT post.*,
    CONCAT('[', GROUP_CONCAT(DISTINCT JSON_OBJECT(
        'id', postComment.id,
        'date', postComment.date,
        'content', postComment.content,
        'user', CONCAT(postComment.fName, postComment.lName)
    ) ORDER BY postComment.id DESC),']') AS comments
FROM posts AS post
    LEFT JOIN (
        SELECT comment.*, commentUser.fName, commentUser.lName
        FROM comments AS comment
            LEFT JOIN users AS commentUser ON comment.uID = commentUser.id
        ORDER BY comment.id DESC
    ) AS postComment ON postComment.postID = post.id
WHERE post.uID = 37
GROUP BY post.id
ORDER BY post.id DESC
LIMIT 0,5;
Due to this limitation, I was thinking of returning only the last 2 comments for each post by adding LIMIT 0,2 to the LEFT JOIN SELECT clause like this:
SELECT post.*,
    CONCAT('[', GROUP_CONCAT(DISTINCT JSON_OBJECT(
        'id', postComment.id,
        'date', postComment.date,
        'content', postComment.content,
        'user', CONCAT(postComment.fName, postComment.lName)
    ) ORDER BY postComment.id DESC),']') AS comments
FROM posts AS post
    LEFT JOIN (
        SELECT comment.*, commentUser.fName, commentUser.lName
        FROM comments AS comment
            LEFT JOIN users AS commentUser ON comment.uID = commentUser.id
        ORDER BY comment.id DESC
        LIMIT 0, 2
    ) AS postComment ON postComment.postID = post.id
WHERE post.uID = 37
GROUP BY post.id
ORDER BY post.id DESC
LIMIT 0,5;
But now it returns the first two comment for the very first post only...
Could anyone tell me how can I get this work correctly, so the query results return the first two comments FOR EACH particular post and why this is happening?
Cheers!
 
    