2016-11-22 79 views
0

我有一個表ContractTable三列這樣如何在SQL中減少兩個關係到一個關係?

ContractID | CompanyID | ContractorID 
-----------+------------+---------- 
    2  | 37725 | 37730 

此表有關係,這種觀點ViewNameList

ID  | CompanyTitle 
-----------+-------------- 
37725  |  X 
37730  |  Y 

我不想得到結果和兩個連接。有一種方法可以像一個關係一樣獲得結果嗎?

ContractID | CompanyID | ContractorID 
-----------+------------+---------- 
    2  |  X  |  Y 

回答

0

您需要JOIN視圖兩次

select y.ContractID,v1.CompanyTitle as CompanyID,v2.CompanyTitle as ContractorID 
from yourtable y 
Left join view v1 on y.CompanyID = v1.ID  
Left join view v2 on y.ContractorID = v2.ID  

如果你不想加入兩次,然後試試這個

SELECT y.ContractID, 
     Max(CASE WHEN y.CompanyID = v.ID THEN v.CompanyTitle END) AS CompanyID, 
     Max(CASE WHEN y.ContractorID = v.ID THEN v.CompanyTitle END) AS ContractorID 
FROM yourtable y 
     JOIN [view] v 
     ON v.ID IN (y.CompanyID, y.ContractorID) 
GROUP BY y.ContractID 
+0

不,我只需要一個連接。 –

+0

@SasanKarimi - 檢查更新 –

+0

非常感謝你@Prdp。有效。 –

0

如果連接是困擾着你,在你能做到這一點不任何連接。即:

SELECT t1.ContractID , 
     (SELECT CompanyTitle FROM ViewNameList t2 WHERE t2.ID = t1.CompanyID) CompanyID, 
     (SELECT CompanyTitle FROM ViewNameList t2 WHERE t2.ID = t1.ContractorID) ContractorID 
     FROM ContractTable t1; 

和當然,Linq中這樣做是很容易:

var contracts = from c in db.Contracts 
       select new { 
        ContractID = c.ContractID, 
        CompanyID = c.Company.CompanyTitle, 
        ContractorID = c.Contractor.CompanyTitle 
       }; 
相關問題