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;
解决方案
您可以使用以下方式执行此操作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
.
推荐阅读
- c# - '无法对 System.Single 和 System.String 执行 'Like' 操作。
- office-ui-fabric - 在 Fluent UI 中使用类似 Toast 的 UI 小部件
- makefile - 如何在英特尔 Pin 工具中使用(编译)zlib(gzip 函数)压缩库?
- android - 为什么“FLAG_BLUR_BEHIND”在 Android 中被弃用?
- angular - Angular 9 - Angular Material mat-paginator 不工作
- python - 循环访问来自网站链接的多个 json 文件
- node.js - nodejs通过其文件内容复制SHA-1加密的纯/文本文件(不解密)
- flutter - Flutter 中的切换按钮
- python - 如何在用户登录后关闭 login.html 文件,使用烧瓶?
- python - 在一个图中可视化多个变量