代码之家  ›  专栏  ›  技术社区  ›  rubyprince

获取具有父表行的最新子行

  •  0
  • rubyprince  · 技术社区  · 5 年前

    两个表格张贴和评论。帖子有很多评论(评论有post\ id外键到posts id主键)

    posts
    
    id | content
    ------------
    
    comments
    
    id | post_id | text | created_at  
    -------------------------------
    

    我需要所有的职位,其内容,和最新的评论(基于max(创建于),及其文本。

    with comment_latest as (select 
       post_id, 
       max(created_at) as latest_commented_at 
    from comments 
    group by 1)
    
    select 
        posts.id, 
        posts.content, 
        comment_latest.latest_commented_at 
    from posts 
    left join comment_latest on comment_latest.post_id = posts.id
    order by posts.id desc 
    limit 10
    

    但我也想要评论的文本。

    1 回复  |  直到 5 年前
        1
  •  2
  •   Gordon Linoff    5 年前

    你可以用Postgres分机 distinct on :

    select distinct on (p.id) p.* c.*
    from posts p left join
         comments c
         on p.id = c.post_id
    order by p.id desc, c.created_at desc
    limit 10;
    

    order by 子句中的键返回第一行 不同于 .