2017-06-19 30 views
2

我有一個意見表,就像這樣:
idanswer_idcontent得到每個答案10條評論通過一個查詢

現在我想每個答案ID最新10條評論。
答案ID列表提供像(1,5,11,27,82)

是否有可能通過一個查詢獲得所有相關評論?

我目前做到這一點通過PHP的的foreach:

foreach ($answers as $answer) { // query mysql for its comments 

回答

1

可以使用UNION ALL每個answer_id:

(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); 
-1
SELECT * FROM comments LIMIT 10; 

LIMIT只會返回指定的沒有結果的。它會返回結果

1

的第n個這是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值更近一些。

+0

@MehdiAzmoudeh。 。 。你可以在任一查詢中放置一個「where」子句。出於性能原因,我會把它們放在子查詢中。 –

+0

@MehdiAzmoudeh。 。 。這是一個更通用的方法。它是否比另一種方法更快取決於您正在使用的系統上的數據,索引和其他因素。 –

相關問題