Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server INNER JOIN multiple inner joins with multiple relations

I have the following query. It works just fine but I need to pull the BUserName from another table named FB that has a UserID field that is related to the UserID in the FU table. Is this possible?

    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 

Just to clarify. I dont have a UserName column in the FB table. It does have FB.UserID which has a relation to FF.UserID which is where I want to pull the second UserName from. So with that relation I am trying to pull the username down from the FF.UserID table that is related to the userID in the FB table. Does this make any sense?

like image 937
nawlrus Avatar asked Mar 23 '12 05:03

nawlrus


1 Answers

You want something like this:

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

Now, FF ties to FU, which then ties to FB. As they are all inner joined, you can use the law of association to understand that this acts like they are all linked together.

 FF = FU   FU = FB    Therefore FF = FB
like image 70
Justin Pihony Avatar answered Sep 26 '22 00:09

Justin Pihony