SQL Server INNER JOIN具有多个关系的多个内部联接

时间:2012-03-23 05:31:38

标签: sql database sql-server-2008

我有以下查询。它工作正常但我需要从另一个名为FB的表中提取BUserName,该表具有与FU表中的UserID相关的UserID字段。这可能吗?

    SELECT TOP 100 
    FF.XID, 
    FF.YID, 
    FF.Title, 
    FF.FileName, 
    FF.FilePath, 
    FU.UserName as FUUserName, 
    FU.UserName as BUserName
    FROM FF 
    INNER JOIN FU ON FU.UserID = FF.UserID 

只是澄清一下。我在FB表中没有UserName列。它确实有FB.UserID,它与FF.UserID有关,这是我想从中提取第二个UserName的地方。因此,在这种关系中,我试图从与FB表中的userID相关的FF.UserID表中拉下用户名。这有意义吗?

5 个答案:

答案 0 :(得分:11)

你想要这样的东西:

SELECT TOP 100 
FF.XID, 
FF.YID, 
FF.Title, 
FF.FileName, 
FF.FilePath, 
FU.UserName as FUUserName, 
FU.UserName as BUserName,
FB.BUserName as FB_BUserName
FROM FF 
    INNER JOIN FU ON FU.UserID = FF.UserID 
    INNER JOIN FB ON FB.UserID = FU.UserID

现在,FFFU绑定,然后绑定到FB。由于它们都是内在的联系,你可以使用结社法来理解这种行为就像它们都是联系在一起的。

 FF = FU   FU = FB    Therefore FF = FB

答案 1 :(得分:0)

喜欢那个?

SELECT TOP 100  
    FF.XID,  
    FF.YID,  
    FF.Title,  
    FF.FileName,  
    FF.FilePath,  
    FU.UserName as FUUserName,  
    FU.UserName as BUserName,
    FB.BUserName  
    FROM FF  
    INNER JOIN FU ON FU.UserID = FF.UserID  
    INNER JOIN FB ON FU.UserID = FB.UserID  

答案 2 :(得分:0)

SELECT TOP 100 
FF.XID, 
FF.YID, 
FF.Title, 
FF.FileName, 
FF.FilePath, 
FU.UserName as FUUserName, 
FB.UserName as BUserName
FROM FF 
INNER JOIN FU ON FU.UserID = FF.UserID 
INNER JOIN FB ON FU.UserID = FB.UserID 

答案 3 :(得分:0)

 SELECT TOP 100 
    FF.XID, 
    FF.YID, 
    FF.Title, 
    FF.FileName, 
    FF.FilePath, 
    FU.UserName as FUUserName, 
    FB.BUserName
    FROM FF 
    INNER JOIN FU ON FU.UserID = FF.UserID 
    INNER JOIN FB ON FB.UserID = FU.UserID

答案 4 :(得分:0)

另外两个例子

1-结果为空:

use my_DB
SELECT tbl_users.UserName
,Updated.UserName   /*Updated not in tbl*/

FROM [my_DB].[dbo].[my_tbl]
left outer join  tbl_users ON tbl_users.UserID = my_tbl.UserID
left outer join tbl_users Updated ON tbl_users.UserID = my_tbl.LasUpdatedUserID

2-结果为空

SELECT tbl_users.UserName
,Updated.UserName   /*Updated not in tbl*/
FROM [my_DB].[dbo].[my_tbl]
INNER JOIN  tbl_users ON tbl_users.UserID = my_tbl.UserID
INNER JOIN tbl_users Updated ON tbl_users.UserID = my_tbl.LasUpdatedUserID

**