在 'outer join left ' 之后如何 select 只有 2 个来自与相同 'common id' 关联的列的数据,当有超过 2 个时..?

After 'outer join left ' how to select only 2 data from column associated with the same 'common id' when there's more than 2..?

我有一个 posts table 列:

id | content 

和评论 table 列:

id | content | post_id

我使用了外左连接:

SELECT posts.id, posts.content,comments.content AS comment_content
FROM posts LEFT JOIN
     comments
     ON comments.post_id = posts.id
ORDER BY posts.id

当我这样做时,我得到了结果集:

正如您在下图中看到的,我从上面的结果集中突出显示了: post 有 3 条评论与之相关..(这里的 id 和内容是 posts)

如何只获得与单个 post id 关联的 2 条评论,而不是与 post id 关联的所有评论。(在本例中,所有与 [=34= 关联的评论]=5 是 3 条评论)

使用row_number():

SELECT p.id, p.content, c.content AS comment_content
FROM posts p LEFT JOIN
     (SELECT c.*,
             ROW_NUMBER() OVER (PARTITION BY c.post_id ORDER BY c.id DESC) as seqnum
      FROM comments c
     ) c
     ON c.post_id = p.id AND c.seqnum <= 2
ORDER BY p.id;

注:以上returns条评论数最高id的两条——大概是最近的评论。如果您想要两个随机评论,请改用 rand()