我如何在Linq中执行此SQL? (左外连接带/日期)

时间:2012-03-03 23:25:37

标签: sql linq sql-server-2008 entity-framework

我的LINQ不是最好的,我的SQL也不是,但我试图在LINQ中做这样的事情(它的伪代码)

select * from CarePlan c 
-- only newest Referral based on r.Date (if more than one exists)
left outer join Referral r on r.CarePlanId = c.CarePlanId 
where c.PatientId = 'E4A1DA8B-F74D-4417-8AC7-B466E3B3FFD0'    

数据如下所示:

  • 患者可以有一堆护理计划
  • 每个护理计划可以有0到n个推荐(我希望每个护理计划提供最新的推荐 - 如果有的话)

想要为每位患者返回一份护理计划清单(无论他们是否有推荐人,如果有多个推荐人,请抓住最新的推荐计划)

感谢任何帮助人员

1 个答案:

答案 0 :(得分:1)

在LINQ中,您使用DefaultIfEmpty来实现左外连接 - http://msdn.microsoft.com/en-us/library/bb397895.aspx处的示例

假设转介不是护理计划中的(可能是空的)集合,那么您将一起加入两个集合......

您的查询类似于:

根据护理计划获取最新推荐信息:

var latestReferrals = from r in referrals  
      group r by r.CarePlanId into lr  
      select new { CarePlanId = lr.Key, LatestReferral = lr.OrderByDescending(lrd => lrd.Date).First()};

查找合并的详细信息:

var q = from c in CarePlan
        where c.PatientId = 'E4A1DA8B-F74D-4417-8AC7-B466E3B3FFD0'
        join lr in latestReferrals on c.CarePlanId equals lr.CarePlanId into gj
        from subReferral in gj.DefaultIfEmpty()
        select new { CarePlanId = c.CarePlanId, LatestReferral = (subReferral == null) ? null : subReferral.LatestReferral };

根据您是想要多个引荐属性还是仅仅几个引用属性,您可能想要或可能不想要第二部分中的整个Referral对象,或者仅提取相关属性。

您可以将这些组合成一个查询,但为了便于阅读,可能更容易将它们分开。如果存在组合解决方案,您还应该比较两种方法的性能。

编辑:看看加入患者/护理计划中其他表格的评论

如果患者从推荐(根据评论)加入,那么它更复杂,因为您正在做几个左外连接。所以切换到稍微简洁的语法:

var combined = from c in carePlans  
where c.PatientId = 'E4A1DA8B-F74D-4417-8AC7-B466E3B3FFD0'   
from lr in latestReferral.Where(r => r.CarePlanId == c.CarePlanId).DefaultIfEmpty()   
from p in patients.Where(patient => patient.PatientId == ((lr != null) ? lr.LatestReferral.PatientId : -1)).DefaultIfEmpty()   
select new { c.CarePlanId, PatientName = (p == null) ? "no patient" : p.PatientName, LatestReferral = (lr == null) ? null : lr.LatestReferral };