如何在Sql中将父表和子表数据作为单个查询获取

时间:2016-07-21 15:38:33

标签: sql sql-server

我想根据userID=user1从2个表中获取所有数据 来自父母和子表,如下图所示 enter image description here

3 个答案:

答案 0 :(得分: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

希望这有帮助!!!

答案 1 :(得分: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

左连接如果不总是匹配

 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  

答案 2 :(得分: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'