简体   繁体   English

内部连接有2个外键到一个主键

[英]Inner joins with 2 foreign keys to one primary key

I have a table called branch (branchid, branchname) and another table called transfer transfer(tranferid, sourcebranch, destinationbranch) 我有一个名为branch(branchid,branchname)的表和另一个名为transfer transfer(tranferid,sourcebranch,destinationbranch)的表

both sourcebranch and destinationbranch are Fk to the branchid of of branch table. sourcebranch和destinationbranch都是Fk到分支表的branchid。 I need to show a query that looks like this 我需要显示一个看起来像这样的查询

Tranferid Source Destination 4 uk us Tranferid Source Destination 4 uk us

but all I can get is something like this 但我能得到的就是这样的

Tranferid Source Destinationid 4 uk 3 Tranferid Source Destinationid 4英国3

query sample 查询样本

select tranferid, branch.branchname, transfer.destinationbranch from transfer inner join branch on branch.branchid == transfer.sourcebranch 从branch.branchid上的transfer inner join分支中选择tranferid,branch.branchname,transfer.destinationbranch == transfer.sourcebranch

How do I get the destination branch to show. 如何显示目标分支。 CTE on my mind CTE在我的脑海里

You need to join table branch on table transfer twice so you can get the value for each column. 您需要在表transfer两次表branch ,以便获取每列的值。

SELECT  a.*, 
        b.branchName AS sourceBranchName,
        c.branchName AS destinationBranchName
FROM    transfer a
        INNER JOIN branch b
            ON a.sourcebranch = b.branchID
        INNER JOIN branch c
            ON a.destinationbranch = c.branchID

To further gain more knowledge about joins, kindly visit the link below: 要进一步了解联接,请访问以下链接:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM