MYSQL Query - Get latest comment related to the post

前端 未结 6 1003
刺人心
刺人心 2021-01-11 20:38

I am trying to get the latest 1 or 2 comments related to each post I download, a bit like instagram does as they show the latest 3 comments for each post, So far I am gettin

6条回答
  •  太阳男子
    2021-01-11 21:24

    You can get there with a pretty simple query by using sub-queries. First I specify the user in the where-clause and join the posts because it seems more logic to me. Then I get all the likes for a post with a sub-query.

    Now instead of grouping and limiting the group size we join only the values we want to by limiting the count of dates after the date we are currently looking at.

    INNER JOIN Activity if you only want to show posts with at least one comment.

    SELECT
      u.id,
      u.username,
      u.fullname,
      u.profileImage,
      p.uuid,
      p.caption,
      p.path,
      p.date,
      (SELECT COUNT(*) FROM Activity v WHERE v.uuidPost = p.uuidPost AND v.type = 'like') likes,
      a.commentText,
      a.date
    FROM
      Users u INNER JOIN
      Posts p ON p.id = u.id LEFT JOIN
      Activity a ON a.uuid = p.uuid AND a.type = 'comment' AND 2 > (
        SELECT COUNT(*) FROM Activity v
        WHERE v.uuid = p.uuid AND v.type = 'comment' AND v.date > a.date)
    WHERE
      u.id = 145
    


    That said a redesign would probably be best, also performance-wise (Activity will soon contain a lot of entries and they always have to be filtered for the desired type). The user table is okay with the id auto-incremented and as primary key. For the posts I would also add an auto-incremented id as primary key and user_id as foreign key (you can also decide what to do on deletion, e.g. with cascade all his posts would also be deleted automatically).

    For the comments and likes you can create separated tables with the two foreign keys user_id and post_id (simple example, like this you can only like posts and nothing else, but if there are not many different kind of likes it could still be good to create a post_likes and few other ..._likes tables, you have to think about how this data is usually queried, if those likes are mostly independent from each other it's probably a good choice).

提交回复
热议问题