【发布时间】:2018-08-19 10:00:24
【问题描述】:
我有一张如图所示的桌子:
我想按日期列出帖子。 如果帖子没有评论发布日期作为日期。 如果帖子有 cmets ,则最后评论日期为发布日期。
结果如图:
对此的 sql 查询是什么?
【问题讨论】:
-
根据您的描述,第一个表中似乎需要有两个日期列,分别是发布日期和评论日期
标签: sql
我有一张如图所示的桌子:
我想按日期列出帖子。 如果帖子没有评论发布日期作为日期。 如果帖子有 cmets ,则最后评论日期为发布日期。
结果如图:
对此的 sql 查询是什么?
【问题讨论】:
标签: sql
select * from YOUR_TABLE_NAME where Parentid is null order by date 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
【讨论】:
这种方法将来自 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);
【讨论】: