2015-11-02 58 views
0

我希望表使用右連接返回來自每個主題的最多2個回覆。我可以知道我該怎麼做?查詢以獲取每個主題的最多2個回覆

Topic table 
+--------+ 
| tid | 
+--------+ 
| 1  | 
| 2  | 
| 3  | 
| 4  | 
+--------+ 


Reply table 
+--------+--------+ 
| rid | tid | 
+--------+--------+ 
| 1  | 1 | 
| 2  | 1 | 
| 3  | 1 | 
| 4  | 2 | 
| 5  | 2 | 
| 6  | 2 | 
| 7  | 4 | 
| 8  | 4 | 
| 9  | 4 | 
+--------+--------+ 

Result 
+--------+--------+ 
| tid | rid | 
+--------+--------+ 
| 1  | 1 | 
| 1  | 2 | 
| 2  | 4 | 
| 2  | 5 | 
| 3  | null | 
| 4  | 7 | 
| 4  | 8 | 
+--------+--------+ 
+0

如果一個主題有2個以上的回覆,那麼使用什麼標準來選擇所選的2? – JRD

+0

@JRD,沒有標準,基於時間或可以隨意任意兩個 – davidlee

+0

本文可能有所幫助:http://www.xaprb.com/blog/2006/12/07/how-to-select-the- firstleastmax排每組合SQL / –

回答

0

這個怎麼樣頂-N查詢:

select tid, rid from(
    select t.tid, r.rid, 
      case when @tid is not null and @tid != t.tid then @rn := 0 else null end reset_rn, 
      @tid := t.tid tid_change, 
      @rn := @rn + 1 rn 
    from topic t 
    left join reply r on t.tid = r.tid 
    join (select @rn := 0, @tid := null) rn 
    order by t.tid, r.rid 
) q 
where rn < 3; 

的關鍵是什麼2行保留在內部查詢的order by