Sql 联接表本身并按最大日期排序

Sql 联接表本身并按最大日期排序,sql,Sql,我有一张如图所示的桌子: 我要按日期排序。 如果帖子没有注释,则发布日期为日期。 如果帖子有评论,则最后评论日期为帖子日期 结果如图所示: 这个的sql查询是什么 从Parentid为空的\u表\u名称中选择*按日期asc排序 我想这对你有帮助 select *,(select max(date) from table as t2 where t2.parentid = t1.postid ) as maxdate from table as t1 where type = '

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

我要按日期排序。 如果帖子没有注释,则发布日期为日期。 如果帖子有评论,则最后评论日期为帖子日期

结果如图所示:


这个的sql查询是什么

从Parentid为空的\u表\u名称中选择*按日期asc排序

我想这对你有帮助

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

此方法将注释中的最长日期与子项中的最长日期合并在一起:

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);

根据您的描述,第一个表中似乎需要有两个日期列,即post date和comment date