如何在同一查询中进行内连接和右外连接

时间:2013-03-20 21:19:05

标签: sql linq

我有这3张桌子:

  1. FeatureTbl(FeatureId(PK),FeatureName)
  2. ParameterTbl(ParameterId(PK),ParameterName)
  3. Map_Parameter_To_Feature(MapId(PK),FeatureId(FK),ParameterId(FK))
  4. 我想将以下SQL转换为LINQ:

    SELECT 
        FeatureTbl.FeatureId,
        FeatureTbl.FeatureName,
        Map_Parameter_To_Feature.ParameterId,
        ParameterTbl.ParameterName
    FROM ParameterTbl
    INNER JOIN Map_Parameter_To_Feature
        ON ParameterTbl.ParameterId = Map_Parameter_To_Feature.ParameterId
    RIGHT OUTER JOIN FeatureTbl
        ON Map_Parameter_To_Feature.FeatureId = FeatureTbl.FeatureId
    

    以上查询返回以下结果

    FeatureId,FeatureName,ParameterId,ParameterName
        1       Feat A      NULL        NULL
        2       Feat B       10         Param X
        3       Feat B       10         Param Y
        4       Feat C      NULL        NULL
    

    我写了以下LINQ:

    (from p in context.ParameterTbls
    join mp2f in context.Map_Parameter_To_Feature 
        on p.ParameterId equals mp2f.ParameterId
    join f in context.FeatureTbls 
        on mp2f.FeatureId equals f.FeatureId
    into desiredresult
    from r in desiredresult.DefaultIfEmpty()
    select new { 
        r.FeatureId,
        r.FeatureName, 
        mp2f.ParameterId, 
        p.ParameterName
    });
    

    但我得到了这个结果

    FeatureId,FeatureName,ParameterId,ParameterName
        2       Feat B       10         Param X
        3       Feat B       10         Param Y
    

    如何将上述SQL转换为LINQ?

1 个答案:

答案 0 :(得分:1)

LINQ没有正确的连接运算符,但您可以将其重写为左连接:

from f in context.FeatureTbls
join mp in (
    from p in context.ParameterTbls
    join mp2f in context.Map_Parameter_To_Feature on p.ParameterId equals mp2f.ParameterId
    select new { mp2f.FeatureId, p.ParameterId, p.ParameterName }
) on f.FeatureId equals mp.FeatureId into ps
from p in ps.DefaultIfEmpty()
select new { f.FeatureId, f.FeatureName, null == p.ParameterId ? (int?)null : p.ParameterId, null == p.ParameterName ? null : p.ParameterName }