2011-04-16 75 views
3

在我的個人資料網站上,用戶可以發表評論,並對評論發表評論(像facebook一樣)。我正在實施一些分頁,因爲在1個配置文件中可能會有數千條評論。分頁工作,但是,由於有孩子的評論,一個簡單的頂部n查詢打破了對話。我只想分析父母的意見,而不是孩子。如何更有效地編寫此查詢?

表「意見」 其中有:

- commentID 
- commentText 
- parentCommentID 
- commentOnUserID 

這裏的問題是,我想只有在那些父母的意見進行分頁(parentCommentID = 0)。所以我寫了一個查詢,如:

select * from Comments c 
where c.parentCommentID = 0 
and c.commentOnUserID = 65939 

(我離開了實際的分頁查詢,因爲這是不相關)

,但我也想加載所有這些評論的孩子的,孩子是還有一條評論,但隨後與parentCommentID =一些評論ID:

select * from comments c 
where c.parentCommentID in (* get the commentId's from the previous query) 
and c.commentOnUserID = 65939 

有沒有辦法有效地結合兩個在1查詢?

回答

2
declare @T table(commentID int, 
       commentText varchar(max), 
       parentCommentID int, 
       commentOnUserID int) 

insert into @T values 
(1, 'Comment 1', 0, 1), 
(2, 'Comment 2', 0, 1), 
(3, 'Comment 3', 0, 1), 
(4, 'Comment 4 sub 1', 1, 1), 
(5, 'Comment 5 sub 1', 1, 1), 
(6, 'Comment 6 sub 1', 1, 1), 
(7, 'Comment 1 sub 2', 2, 1), 
(8, 'Comment 1 sub 2', 2, 1), 
(9, 'Comment 1 sub 3', 3, 1) 

declare @UserID int = 1 

;with cte as 
(
    select 
    T.commentID, 
    T.CommentText, 
    row_number() over(order by commentID) as rn 
    from @T as T 
    where 
    T.parentCommentID = 0 and 
    T.commentOnUserID = @UserID 
    union all 
    select 
    T.commentID, 
    T.CommentText, 
    C.rn 
    from @T as T 
    inner join cte as C 
     on T.parentCommentID = C.commentID 
) 
select * 
from cte 
where rn between 1 and 2 -- use rn for pagination 
order by rn, commentID 

結果

commentID parentCommentID CommentText   rn 
----------- --------------- -------------------- -------------------- 
1   0    Comment 1   1 
4   1    Comment 4 sub 1  1 
5   1    Comment 5 sub 1  1 
6   1    Comment 6 sub 1  1 
2   0    Comment 2   2 
7   2    Comment 1 sub 2  2 
8   2    Comment 1 sub 2  2 
1

事情是這樣的:

WITH 
    ParentComment AS (
     SELECT * from Comments c 
     WHERE c.parentCommentID = 0 
     AND c.commentOnUserID = 65939 
    ) 
SELECT * 
FROM Comments c 
WHERE c.commentOnUserID = 65939 
AND (
    c.CommentID IN (SELECT CommentID FROM ParentComment) 
    OR c.ParentCommentID IN (SELECT CommentID FROM ParentComment) 
) 

沒有測試在SQL Server中的語法,但應該是一般的想法。

0

我會做這在類似如下的方式:

SELECT p.*, c.* 
FROM comment c LEFT JOIN comment p ON (c.parentCommentID = p.commentID) 
WHERE p.parentCommentID = 0 
AND p.commentOnUserID = 65939 

我敢肯定有一些辦法,包括在子女的父或母,結果很好,但我知道在MySQL中至少有性能問題在加入條件下放置一個OR。