2012-07-10 118 views
0

我一直在嘗試這項要求幾個小時,但即時通訊,因爲我沒有得到所需的結果。Mysql 2表連接限制結果返回從這兩個表

我有兩張桌子。

**Main Comment Table 
---------------------------------------------------------------------------- 
id | comments | date_commented | comment_owner | commented_by 
1 hello world **********  321    123 

Child Comment Table 
---------------------------------------------------------------------------- 
id | mainpostID| child_comment_data   | commented_by | date_commented** 
1  1   child comment of hello world 456    ******** 

我的要求:
我想與Chilcomments沿着取得前10的主要評價每一個主要的意見。我希望將每條主評論的子評論數量限制爲5個。

我的嘗試:

SELECT maincomment.comments, childcomment.child_comment_data 
FROM maincomment 
LEFT JOIN childcomment ON maincomment.id = childcomment.mainpostID 
AND maincomment.comment_owner = childcomment.commented_by 
WHERE maincomment.id = childcomment.mainpostID 
ORDER BY dateposted DESC 
LIMIT 10 

結果:IM只得到10 Maincomments但childcomments數量僅有1爲每個主要的意見。我需要的是爲每個Maincomment返回5個孩子評論。

有沒有人請幫忙提出一些建議/在這裏查詢。

非常感謝。

回答

1

您可以使用此解決方案:

SELECT a.*, b.* 
FROM 
(
    SELECT * 
    FROM maincomment 
    ORDER BY dateposted DESC 
    LIMIT 10 
) a 
LEFT JOIN 
(
    SELECT a.* 
    FROM childcomment a 
    INNER JOIN childcomment b ON a.mainpostID = b.mainpostID AND a.id <= b.id 
    GROUP BY a.id 
    HAVING COUNT(1) <= 5 
) b ON a.id = b.mainpostID 
ORDER BY a.dateposted DESC, b.date_commented DESC 

這得到了多達10個最新的主評論5最新兒童的意見。如果沒有特定主註釋的子註釋,子註釋數據將包含NULL值。