MYSQL Query - Get latest comment related to the post

前端 未结 6 1002
刺人心
刺人心 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:17

    I am a little bit lost in your query, but if you want to download data for multiple posts at once, it's not a good idea to include comment data in the first query since you would include all the data about post and posting user multiple times. You should run another query that would connect posts with comments. Something like:

    SELECT 
    A.UUIDPost, 
    C.username,
    C.profileImage, 
    B.Comment,
    B.[DateField]
    FROM Posts A JOIN 
    Activities B ON A.uuid = B.UUIDPost JOIN
    Users C ON B.[UserId] = C.id 
    

    and use that data to display your comments with commenting user id, name, image etc.

    To get only 3 comments per post, you can look into this post:

    Select top 3 values from each group in a table with SQL

    if you are sure that there are going to be no duplicate rows in the comment table or this post:

    How to select top 3 values from each group in a table with SQL which have duplicates

    if you're not sure about that (although due to DateField in the table, it should not be possible).

提交回复
热议问题