通过 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 `co
mment` 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说明:
结果:
此查询将返回一个数据集结构,其中每个文章包含其内容和关联的前 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"
}
]
},
// ...其他文章的数据
]