2010-03-17 66 views
0

我有一個查詢,當前查詢Post表,而左加入Comment表。它提取所有帖子及其相應的評論。不過,我想限制返回的評論數量。我嘗試添加一個子選擇,但遇到錯誤,如果我沒有將結果限制爲1.我真的不知道如何去處理這個問題,而仍然只使用一個查詢。這可能嗎?是否可以限制JOIN查詢的結果?

+1

如果您發佈當前查詢,則可以獲得更好的結果。 – 2010-03-17 21:04:32

回答

2

這一個應該得到每個崗位的三個最新評論你的帖子,假設您的表看起來像:


idpost_text

評論
idpost_idcomment_text

SELECT id, post_text, comment_text 
FROM 
(
    SELECT p.id, p.post_text, c.comment_text 
      CASE 
      WHEN @id != p.id THEN @row_num := 1 
      ELSE @row_num := @row_num + 1 
      END AS rank, 
      @id := p.id 
    FROM post p 
    LEFT JOIN comment c ON (c.post_id = p.id) 
    JOIN (SELECT @id:=NULL, @row_num:=0) x 
    ORDER BY p.id, 
      c.id DESC -- newest comments first 
) y 
WHERE rank <= 3; 

子查詢用於首先獲取最近的評論併爲每個帖子編號,而外層選擇刪除較舊的評論。

1

除非您有方便的過濾值(例如where pos between 1 and 5),否則無法限制連接。您可以分別選擇第一條評論,第二條評論,第三條評論等,併合並結果。一些醜陋這樣的:

select This, That 
from Post 
left join (
    select Some 
    from Comment 
    where PostId = Post.Id 
    order by CreatedDate 
    limit 1,1 
) x on 1=1 

union all 

select This, That 
from Post 
inner join (
    select Some 
    from Comment 
    where PostId = Post.Id 
    order by CreatedDate 
    limit 2,1 
) x on 1=1 

union all 

select This, That 
from Post 
inner join (
    select Some 
    from Comment 
    where PostId = Post.Id 
    order by CreatedDate 
    limit 3,1 
) x on 1=1