
通过 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 youjiankuohaophpcn (select count(id) from `comment` b where b.pid = a.pid and a.id youjiankuohaophpcn b.id)
order by
a.id desc) tmp
join article tmp1 on tmp.pid = tmp1.id说明:
- 子查询:此子查询从 comment 表中提取每个文章的前 5 条评论。
- 条件:子查询中的 where 子句检查每个评论是否在前 5 条评论之内。
- 降序排序:子查询中的 order by 子句将评论按降序排列,以获得最早的评论。
- join:外部查询将子查询与 article 表连接,使用 pid 列匹配文章和评论。
结果:
此查询将返回一个数据集结构,其中每个文章包含其内容和关联的前 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"
}
]
},
// ...其他文章的数据
]










