2

我有一个sql查询,它有innerjoin和leftouter join,这对于mr转换为LINQ来说非常棘手。

SELECT project.ID, project.No, project.Name,  
       APPLN.Id,APPLN.Name,SAR.Name  
FROM Phasefact phase WITH (NOLOCK)  
INNER JOIN AProject project WITH (NOLOCK) on phase.Id = project.ID
INNER JOIN Application APPLN WITH (NOLOCK) ON project.AppId = APPLN.Id
LEFT OUTER JOIN Master master WITH (NOLOCK) ON phase.amId = master.Id
INNER JOIN Ref SAR WITH (NOLOCK) ON SAR.ID = master.Ref_Id
WHERE phase.ID = 123    

这有点令人困惑,因为它包含“左外连接”。有人请帮忙。

4

2 回答 2

2

也许是这样的:

var result=(
        from phase in db.Phasefact
        join project in db.AProject
            on phase.Id equals project.ID
        join APPLN in db.Application 
            on project.AppId equals APPLN.Id
        //Left join
        from master in db.Master
            .Where(a=>a.Id==phase.amId).DefaultIfEmpty()
        join SAR in db.Ref
            on SAR.ID equals master.Ref_Id
        where phase.ID == 123 
        select new
        {
            project.ID,
            project.No,
            project.Name,  
            APPLN.Id,
            APPLN.Name,
            SAR.Name
        }
    );

编辑

但我不明白left join。你为什么用一个left join?对我来说,您似乎首先使用 a left join

LEFT OUTER JOIN Master master WITH (NOLOCK) ON phase.amId = master.Id

之后你有一个限制结果的连接,如下所示:

INNER JOIN Ref SAR WITH (NOLOCK) ON SAR.ID = master.Ref_Id

这与执行此操作相同:

INNER JOIN Master master WITH (NOLOCK) ON phase.amId = master.Id
INNER JOIN Ref SAR WITH (NOLOCK) ON SAR.ID = master.Ref_Id
于 2012-05-10T06:51:09.760 回答
0

我正在向您介绍 LINQ 中左外连接的基本概念

var lines = from p in db.Phasefact
join m in db.Master on m.Id 等于 p.amId into p_m 其中 p.ID == 123 from m in p_m.DefaultIfEmpty() select new { p.ID };

现在您可以根据您的逻辑进行更多转换......或查询......

于 2012-05-10T06:48:22.567 回答