2016-04-14 208 views
0

我想根據多個字段連接表,其中一個來自直接表,另一個來自鄰接表。使用跨多個表的多個字段來連接表

enter image description here

我想加入的「裝備」,以「合同細節」上ContractDetailID只有當設備客戶id =合同客戶ID。

+1

您正在使用哪個數據庫管理系統預先感謝您?你也可能想閱讀:http://meta.stackoverflow.com/questions/285551/why-may-i-not-upload-images-of-code-on-so-when-asking-a-question/ 285557#285557 –

+0

Microsoft SQL DB – Charles

+0

[SQL join multiple tables]可能重複(http://stackoverflow.com/questions/9853586/sql-join-multiple-tables) –

回答

0
declare @contract as table(
    contractid int, 
    customerid int 
) 

declare @contractDetail as table(
    contractDetailId int, 
    ContractID int 
) 

declare @equipment as table(
    equipmentId int, 
    contractDetailId int, 
    CustomerId int 
) 

insert into @contract values(5,3) 
insert into @contractDetail values(10,5) 
insert into @equipment values(1,10,3) 

select e.* 
from 
    @contract c inner join 
    @contractDetail cd on (c.contractId = cd.contractID) inner join 
    @equipment e on (c.customerId = e.CustomerId and e.contractDetailId = cd.contractDetailId)