通过 sql 查询文章及其前 5 条评论
简介:
您需要查询所有文章及其关联的评论,但每篇文章最多显示前 5 条评论。传统的 left join 查询无法满足此限制。本文将提供一种 sql 解决方法,以提取所需的数据。
sql 查询:
select tmp1.id, tmp1.content, tmp.comment from (select a.pid, a.comment from `comment` a where 5 > (select count(id) from `comment` b where b.pid = a.pid and a.id > b.id) order by a.id desc) tmp join article tmp1 on tmp.pid = tmp1.id
说明:
结果:
此查询将返回一个数据集结构,其中每个文章包含其内容和关联的前 5 条评论。输出示例:
[ { "id": 1, "content": "文章内容 1", "commentList": [ { "commentid": 1, "comment": "评论 1" }, { "commentid": 2, "comment": "评论 2" }, { "commentid": 3, "comment": "评论 3" }, { "commentid": 4, "comment": "评论 4" }, { "commentid": 5, "comment": "评论 5" } ] }, // ...其他文章的数据 ]
以上就是如何使用 SQL 查询获取文章及其前 5 条评论?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号