2012-03-26 104 views
0

这是我的LINQ查询Linq查询与LEFT JOIN有多个表

from row in (
    from c in db.TabC 
    from cpd in db.TabPD 
    from slm in db.TabSLM 
    where cpd.SLid == slm.SLid 
    where c.Id == cpd.CID 
    where c.O_Id == 1 
    select new { c, cpd, slm }) 
group row in row.slm.SLType into g 
select new 
{ 
    SLType = g.Key, 
    EStat = g.Count(r => r.c.EstatID != null), 
    Training = g.Count(r => r.cpd.TrId != null), 
    TrainingComplete = 
     g.Count(r => r.cpd.TrStat == 44), 
    AssessmentComplete = 
     g.Count(r => r.cpd.CndAssess == 44) 
}; 

我需要一个左连接表db.TabSLM并且有在该表中获得尽可能多的记录。 TabC是一个主表,TabSLM也是。 TabPD具有引用TabC和TabSLM的详细记录。使用此查询,当TabPD中没有匹配的TabC rowid或TabSLM rowid时,我不会返回任何记录。我想要的是返回TabSLM中存在的记录数,因为没有匹配。有关如何修改此查询的任何想法?

这里是下面是每个最小领域的三个表的样本数据中列出

TabC 
ID O_ID Name 
1  1  ABC 
2  1  XYZ 
3  1  RST 

TabPD 
RowID CID SLid 
1  2  1 
2  1  1 
3  3  2 
4  ... 

TabSLM 
SLid SLType 
1  single level 
2  Multi level 

与查询以上,我能够得到记录,其中TabC.O_ID == 1,但不是哪里TabC.O_ID == 3,因为TabC.O_ID没有我还是想与其他列显示为0

感谢您的时间,以显示与SLType ID == 3.任何记录......

回答

2

您需要使用DefaultIfEmpty

var query = 
    from row in (
     from c in db.TabC 
     join cpd in db.TabPD on c.Id equals cpd.CID 
     from slm in db.TabSLM.Where(x => cpd.SLid == x.SLid) 
          .DefaultIfEmpty() 
     where c.O_Id == 1 
     select new { c, cpd, slm }) 
group row by row.slm.SLType into g 
select new 
{ 
    SLType = g.Key, 
    EStat = g.Count(r => r.c.EstatID != null), 
    Training = g.Count(r => r.cpd.TrId != null), 
    TrainingComplete = 
     g.Count(r => r.cpd.TrStat == 44), 
    AssessmentComplete = 
     g.Count(r => r.cpd.CndAssess == 44) 
}; 
+0

没有工作。我在这里仍然没有记录。 – user20358 2012-03-26 16:37:48

+0

此外,“将row.slm.SLType中的行组合到g中”不起作用。 “将row.slm.SLType分组到g”中。 – user20358 2012-03-26 16:54:22

+0

@ user20358 - 我稍微更新了查询。没有看到表* TabC *,* TabPD *,* TabSLM *我将无法知道预期的结果 – Aducci 2012-03-26 16:55:37

0

刚刚尝试这一次,

var query = 
    from row in (
     from c in db.TabC 
     join cpd in db.TabPD on c.Id equals cpd.CID into temp 
          from cpd in temp.DefaultIfEmpty() 
     from slm in db.TabSLM.Where(x => cpd.SLid == x.SLid) 
          .DefaultIfEmpty() 
     where c.O_Id == 1 
     select new { c, cpd, slm }) 
group row by row.slm.SLType into g 
select new 
{ 
    SLType = g.Key, 
    EStat = g.Count(r => r.c.EstatID != null), 
    Training = g.Count(r => r.cpd.TrId != null), 
    TrainingComplete = 
     g.Count(r => r.cpd.TrStat == 44), 
    AssessmentComplete = 
     g.Count(r => r.cpd.CndAssess == 44) 
};