如何从特定的新消息中获取最新评论?

时间:2019-04-04 09:54:06

标签: sql

我有一张桌子

News(newsId, text, date) 

Comments(commentId, text, date, newsId) 

,我需要按日期选择10条最新新闻,并从每条新闻中获得最新评论。到目前为止,我已经有了,该如何改进并完成它?

  SELECT date, 
         newsId, 
         commentid, 
         date
    FROM News, 
         comments
ORDER BY date DESC
   LIMIT 10;

3 个答案:

答案 0 :(得分:0)

如果您的dbms支持row_number,则可以尝试以下操作

with cte as
(select *,row_number()over(partition by newsId order by date desc) rn
from News
), cte1 as
(
select newsId, text, date from cte where rn<=10
) select cte1.*,c.commentId,c.text as commnt from cte1 join Comments c on cte1.newsid=c.newsid

答案 1 :(得分:0)

对于较早的DBMS子查询将很有用:

select n.newsid, n.text, n.text, n.date, c.text as comment 
from news n inner join
     comments c
     on c.newsId = n.newsId
where c.date in (select c1.date 
                 from comments c1 
                 where c1.newsid = n.newsid 
                 order by c1.date desc
                 limit 10
                );

但是,对于最新版本的DBMS row_number(),通常可以执行此操作。

答案 2 :(得分:0)

您可以使用row_number()来做到这一点:

select n.newsid, n.text, n.text, n.date, c.text as comment 
from news n left join
     (select c.*,
             row_number() over (partition by c.newsid order by date desc) as seqnum
      from comments c
     ) c
     on c.newsId = n.newsId and seqnum = 1
order by n.date desc
limit 10;

请注意,这将返回没有评论的新闻项目。如果您不想要这些,请将left join更改为inner join