【问题标题】:join table themselves and order by max date自己加入表并按最大日期排序
【发布时间】:2018-08-19 10:00:24
【问题描述】:

我有一张如图所示的桌子:

我想按日期列出帖子。 如果帖子没有评论发布日期作为日期。 如果帖子有 cmets ,则最后评论日期为发布日期。

结果如图:

对此的 sql 查询是什么?

【问题讨论】:

  • 根据您的描述,第一个表中似乎需要有两个日期列,分别是发布日期和评论日期

标签: sql


【解决方案1】:

select * from YOUR_TABLE_NAME where Parentid is null order by date asc;

【讨论】:

    【解决方案2】:

    我想这会对你有所帮助。

    select *,(select max(date) from table as t2 where t2.parentid = t1.postid ) as maxdate 
       from table as t1 
       where type = 'P'
       order by maxdate asc
    

    【讨论】:

      【解决方案3】:

      这种方法将来自 cmets 的最大日期与来自子项的最大日期合并:

      select p.*,
             coalesce(p2.maxdate, p.date) as date
      from posts p left join
           (select p2.parentid, max(p2.date) as maxdate
            from posts p2
            where p2.parentid is not null
            group by p2.parentid
           ) pc
           on pc.parentid = p.postid
      where p.type = 'P'
      order by coalesce(p2.maxdate, p.date) asc;
      

      如果您想要更少的列(获取所有列有点麻烦),还有另一种使用聚合的有趣方法。

      仅获取每个帖子的日期:

      select coalesce(parentid, postid) as postid,
             max(date)
      from posts p  
      group by  coalesce(parentid, postid);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-05-06
        • 2021-01-02
        • 1970-01-01
        • 1970-01-01
        • 2016-01-21
        • 1970-01-01
        • 1970-01-01
        • 2019-07-25
        相关资源
        最近更新 更多