如何在SQL Server的一个查询中多个连接多个表

时间:2013-06-14 08:21:37

标签: sql sql-server

我在使用SQL Server的C#项目上工作。

我想在查询中连接多个表(或在单个查询中运行多个语句)

我的疑问是:

(select HR.ID, HR.Cod, HR.CodeValed, H.Onvan, H.Model from HR LEFT JOIN H ON HR.ID_Sefat = H.ID) AAA;
SELECT GG.Cod G
FROM 
(Select * From AAA Where AAA.Model = 'M') MM
Left JOIN (Select * From AAA Where AAA.Model = 'K') KK ON MM.CodeValed = KK.Cod
Left JOIN (Select * From AAA Where AAA.Model = 'G') GG ON KK.CodeValed = GG.Cod

但它不起作用,它会返回错误。

解决此问题的最佳方法是什么?

1 个答案:

答案 0 :(得分:2)

试试这个:

with AAA as 
(select HR.ID, HR.Cod, HR.CodeValed, H.Onvan, H.Model from HR 
LEFT JOIN H ON HR.ID_Sefat = H.ID) 
SELECT GG.Cod G
FROM 
(Select * From AAA Where AAA.Model = 'M') MM
Left JOIN (Select * From AAA Where AAA.Model = 'K') KK ON MM.CodeValed = KK.Cod
Left JOIN (Select * From AAA Where AAA.Model = 'G') GG ON KK.CodeValed = GG.Cod