2012-06-06 20 views
0

我想在三個表上執行左外連接。我知道有一種方法可以在一個變量中完成,但我一直無法弄清楚。相反,我已經執行了兩個單獨的左外部連接,然後對這些連接進行了省略操作。這裏是我的代碼爲:尋找更好的方法來執行LINQ中的三個表上的左外連接

var outerJoin1 =  

    (from h in resultHours 
    join u in results on new {h.PhysicalUnitId, h.MonthNum} equals new {u.PhysicalUnitId, u.MonthNum} into outer 
    from grouping in outer.DefaultIfEmpty() 
    select new {timeKey = h, Key = grouping}); 

var outerJoin2 =  

    (from h in resultHours 
    join s in serviceHrsResults on new {h.PhysicalUnitId, h.MonthNum} equals new {s.PhysicalUnitId, s.MonthNum} into outer2 
    from grouping in outer2.DefaultIfEmpty() 
    select new {timeKey = h, Key = grouping}); 

var outerJoin = 

    (from a in outerJoin1 
    join b in outerJoin2 on new {a.timeKey.PlantId, a.timeKey.MonthNum} equals new {b.timeKey.PlantId, b.timeKey.MonthNum} into outer 
    from grouping in outer.DefaultIfEmpty() 
    select new{timeKey = a, Key = grouping}).Distinct(); 

我已經嘗試把上述在一起在一個變量我無法得到它的工作。這是我曾嘗試過的:

var outerjoin = 

    from h in resultHours 
    join u in results on new {h.PhysicalUnitId, h.MonthNum} equals new {u.PhysicalUnitId, u.MonthNum} into outer 
    from grouping in outer.DefaultIfEmpty() 
    from hr in resultHours 
    join s in serviceHrsResults on new {hr.PhysicalUnitId, hr.MonthNum} equals new {s.PhysicalUnitId, s.MonthNum} into outer2 
    from grouping in outer2.DefaultIfEmpty() 
    select new {timeKey = h && timeKey = hr, Key = grouping}; 

問題在於這是兩個分組衝突。我敢肯定,我只需要在選擇之前進行單一分組,但無法弄清楚如何使用「分組」,並且同時包含outer.DefaultIfEmpty()和outer2.DefaultIfEmpty()。

如果有人能夠啓發我,我將不勝感激。

回答

1

您正在使用重複的範圍變量id - 您有2x grouping
- 您希望在結果集中使用哪個分組? - 這條線預計會達到什麼? timeKey = h && timeKey = hr - 你想如何結合投影中的那些?

我會嘗試下面的查詢,但我已經改變了select的一部分,因爲你的組合版本對我來說沒有意義。

讓我知道它是否適合你,因爲沒有數據這不容易測試,所以我不能確定新版本是否正常。

var outerjoin = 
    from h in resultHours 
    join u in results on new {h.PhysicalUnitId, h.MonthNum} equals new {u.PhysicalUnitId, u.MonthNum} into outer 
    from grouping1 in outer.DefaultIfEmpty() 
    //from hr in resultHours 
    join s in serviceHrsResults on new {grouping1.PhysicalUnitId, grouping1.MonthNum} equals new {s.PhysicalUnitId, s.MonthNum} into outer2 
    from grouping2 in outer2.DefaultIfEmpty() 
    select new {timeKey = h, Key1 = grouping1, Key2 = grouping2};