首页 > 解决方案 > 如何从特定的新消息中获取最新评论?

问题描述

我有一张桌子

News(newsId, text, date) 

Comments(commentId, text, date, newsId) 

我需要按日期选择 10 条最新消息,每条消息都有最新评论。到目前为止,我有这个,我该如何改进并完成它?

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

标签: sql

解决方案


您可以使用以下方式执行此操作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 joininner join.


推荐阅读