将另一个表中的用户名提取到包含两个具有UserID的字段的表中

时间:2014-09-01 04:21:24

标签: c# sql

我有两个表格,tblUsertblForward,其中包含以下列:

tblUser

UserID             
Username 

tblForward

ForwardID     
ForwardedToUserID  (--> tblUser.UserID)
ForwardedFromUserID  (--> tblUser.UserID)

现在我要做的是使用UsernametblUserForwardedToUserID获取ForwardedFromUserID并显示Username(不是UserID当我从tblForward获取数据时。

我该怎么做?

3 个答案:

答案 0 :(得分:0)

IN OP想要连接ForwardedToUserID and ForwardedFromUserID

select max(Fromuser),max(ToUser) from (
  select UserName as Fromuser, '' as ToUser from tblUsers A  
  inner join  tblForward B ON A.UserID = B.ForwardedToUserID 
  union all
  select '' as Fromuser, UserName as ToUser  from tblUsers A  
  inner join  tblForward B ON A.UserID = B.ForwardedFromUserID) as t

答案 1 :(得分:0)

我建议你这样做:

SELECT A.UserName, B.UserName AS ForwardedToUserName, C.UserName AS ForwardedFromUserName
FROM tblUsers A 
    INNER JOIN tblForward B ON A.UserID = B.ForwardedToUserID
    INNER JOIN tblForward C ON A.UserID = C.ForwardedFromUserID

因为它返回所有用户ID的相关用户名

答案 2 :(得分:-1)

您需要做的是使用join statement

SELECT A.UserName from tblUsers A 
inner join tblForward B on 
     A.UserID = B.ForwardedToUserID
     OR A.UserID = B.ForwardedFromUserID