选择具有相同ID的数量限制

时间:2019-04-24 10:47:47

标签: sql mariadb greatest-n-per-group

我有3张桌子

帖子评论

comment_id, comment_post_id, comment_value, comment_time comment_user_id
1           1                test           DATETIME     1
2           1                test2          DATETIME     2
3           2                test3          DATETIME     2
4           1                test4          DATETIME     2
5           1                test5          DATETIME     1
6           1                test6          DATETIME     2

会员

member_id member_fistname member_lastname member_slug
1         John            Doe             john-doe
2         Test            User            test-user

会员照片

member_user_id member_photo_type member_photo_name
1              2                 test.jpg
2              2                 test2.jpg

我有sql

SELECT 
      posts_comments.comment_id, 
      posts_comments.comment_post_id, 
      posts_comments.comment_value, 
      posts_comments.comment_time, 
      members.member_id, 
      members.member_lastname, 
      members.member_fistname, 
      members_photos.member_photo_name 
FROM 
    posts_comments 
LEFT JOIN 
         members ON posts_comments.comment_user_id = members.member_id 
LEFT JOIN 
         members_photos ON members.member_id = members_photos.member_user_id 
AND 
   members_photos.member_photo_type = 2 
ORDER BY 
        posts_comments.comment_time DESC 
LIMIT 4

但是此查询仅显示最后4条评论,而与comment_post_id无关。 在这种情况下,我想为每个comment_post_id显示最后4条评论(在此示例中:4条评论,其中comment_post_id = 1,1条评论,其中comment_post_id = 2)。 我希望我写得足够清楚。 Thx 4帮助:)

1 个答案:

答案 0 :(得分:1)

如果mariadb版本为row_number()或更高版本,请使用MariaDB 10.2.0窗口函数

select a.* from (    SELECT 
              posts_comments.comment_id, 
              posts_comments.comment_post_id, 
              posts_comments.comment_value, 
              posts_comments.comment_time, 
              members.member_id, 
              members.member_lastname, 
              members.member_fistname, 
              members_photos.member_photo_name,
             row_number()over(partition by  posts_comments.comment_post_id order by posts_comments.comment_time desc) rn
        FROM 
            posts_comments 
        LEFT JOIN 
                 members ON posts_comments.comment_user_id = members.member_id 
        LEFT JOIN 
                 members_photos ON members.member_id = members_photos.member_user_id 
        AND 
           members_photos.member_photo_type = 2
    ) a where a.rn<=4