我有一个评论表,如下所示:
id
,answer_id
,content
现在我想获得每个答案ID的最新10条评论 答案ID列表如(1,5,11,27,82)
是否可以通过一个查询获取所有相关评论?
我目前通过php的foreach:
执行此操作foreach ($answers as $answer) { // query mysql for its comments
答案 0 :(得分:1)
这是MySQL的痛苦,但您可以使用变量:
select c.*
from (select c.*,
(@rn := if(@a = c.answer_id, @rn + 1,
if(@a := c.answer_id, 1, 1)
)
) as rn
from comments c cross join
(select @rn := 0, @a := -1) params
order by answer_id, id desc
) c
where rn <= 10;
这假设较大的id
值更新。
答案 1 :(得分:1)
您可以为每个answer_id使用UNION ALL
:
(select id, answer_id, content from comments where answer_id=1 order by id desc limit 10)
union all
(select id, answer_id, content from comments where answer_id=5 order by id desc limit 10)
union all
(select id, answer_id, content from comments where answer_id=11 order by id desc limit 10)
union all
(select id, answer_id, content from comments where answer_id=27 order by id desc limit 10)
union all
(select id, answer_id, content from comments where answer_id=82 order by id desc limit 10);
答案 2 :(得分:-1)
SELECT * FROM comments LIMIT 10;
LIMIT
将仅返回指定的结果数。它将返回前n个结果