Skip to content
Advertisement

Explain what means to join same table twice

I was preparing for exam and I have this exercise that I don’t understand

I have table of Clients that have ClientID, and also I have table of Transactions that have Foreign Key referenced to Clients, SenderID and RecieverID (refering to ClientID)

I need to create view that will show Transactions with Sender name and Reciever Name, and I did it but I don’t understand how it works and why

Here is code:

SELECT CS.Name [SenderName], CR.Name [RecieverName]
FROM Transactions T
INNER JOIN Clients CS
ON CS.ClientID = T.SenderID
INNER JOIN Clients CR
ON CR.ClientID = T.RecieverID

Advertisement

Answer

Each time you need the name (for sender or recevier ) you need a relation based on the key between the the transaction table and the clients table

you need the name of the sender ( first join with Clients ) and the name for recevier ( second join with Clients )

for avoid confusion between the two (same name) table you need an alias that let you join the specific related tabe .. you use CS and CR as table nale alias

in this way is as you work with two differente table name (or with a logical duplication of the same table)

 SELECT CS.Name [SenderName], CR.Name [RecieverName]
    FROM Transactions T
    INNER JOIN Clients CS  ON CS.ClientID = T.SenderID
    INNER JOIN Clients CR  ON CR.ClientID = T.RecieverID

You can thinks at the table content as a set of data ..so you use two time the same set of data extracting the row mathcing your relation each time.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement