2016-07-21 33 views

回答

1

我認爲這應該工作:

SELECT  parent.CommentID as CommentID, 
      parent.userID as userID, 
      parent.Message as Message, 
      parent.Date as date, 
      NULL as ParentCommentID 
FROM  #ParentComment parent 
WHERE  UserID = 'user1' 

UNION 

SELECT  child.c_commentID as CommentID, 
      child.c_userID as userID, 
      child.c_message as Message, 
      child.c_Date as date, 
      child.c_parentcommentID as ParentCommentID 
FROM  #ChildComment child 
WHERE  child.c_userID = 'user1' 

下面是一個SQL小提琴:http://sqlfiddle.com/#!9/3bb46/2

希望這有助於!

+0

其工作,你節省了我的時間兄弟...謝謝 – user6503334

+0

@ user6503334很高興幫助。這也很簡單。 –

0

使用加入

內連接如果ID總是與

select 
    a.CommentID as CommentI 
    ,a.userID, as userID 
    , a.Message as Message 
    , a.Date as date 
    , b.c_commentID as parent__comment_id 
    from parent_comment as a 
inner join child_comment as b on a.commentID = b.c_commentID 

LEFT JOIN如果並不總是一致的

select 
    a.CommentID as CommentI 
    ,a.userID, as userID 
    , a.Message as Message 
    , a.Date as date 
    , b.c_commentID as parent__comment_id 
    from parent_comment as a 
left join child_comment as b on a.commentID = b.c_commentID 
+0

,但它會顯示像這樣的commentID,userID,Message,Date,c_commentID,c_userID,c_Message ,c_Date,c_ParentcommentID – user6503334

+0

有什麼問題..如果你只需要一些列..設置你需要的列名稱。 – scaisEdge

0

只需使用左與工會參加類似這樣的例子

Select TP.* 
    FROM ParentTable as TP LEFT JOIN ChildTable as TC 
    ON TC.c_ParentcommentID = TP.commentID AND TC.c_ParentcommentID = null 
    WHERE TP.userID='user1' 
UNION ALL 
Select TC.c_CommnetID as CommentID , TC.c_userID as userID , TC.c_Message as Message , TC.Date as 'Date' 
    FROM ChildTable as TC inner join ParentTable as TP 
    ON TC.c_ParentcommentID = TP.commentID 
    WHERE TC.userID='user1' 
相關問題