如何在连接字段为空或 0 时执行左连接

How to perform a left join when joined field is null or 0

我有两个具有一对多关系的表:WorkOrder 1 - * Service

他们通过字段建立关系:ServiceID

由于一些遗留的原因,有些WorkOrder没有任何Service,但是它的ServiceID字段被保存为0


现在我要select全部WorkOrdersiff​​

有一个匹配的 ServiceWorkOrderServiceID = 0

如果没有 ServiceID = 0 要求,它应该是一个正常的左连接:

 var result = from wo in WorkOrderQuery
              join j in JobQuery on ... // join some other tables
              join s in ServiceQuery on wo.ServiceID equals s.ServiceID into gg
              from g in gg.DefaultIfEmpty()
              select new 
              {
                 ServiceCode = g == null? "" : g.Code,
                 WorkOrderID = wo.WorkOrderID,
              };

但我不知道这个要求是什么时候增加的。任何建议表示赞赏。

不确定我是否理解,但试试这个:

var result = (from wo in WorkOrderQuery
              join s in ServiceQuery on wo.ServiceID equals s.ServiceID into g
              from s in g.DefaultIfEmpty()
              where wo.ServiceID == 0 || s != null
              select new 
              {
                  ServiceCode = s?.Code ?? string.Empty,
                  WorkOrderID = wo.WorkOrderID
              }).ToList();

测试此数据:

List<dynamic> WorkOrderQuery = new List<dynamic>
{
    new { WorkOrderID = 1, ServiceID = 1 },
    new { WorkOrderID = 2, ServiceID = 2 },
    new { WorkOrderID = 3, ServiceID = 0 }
};

List<dynamic> ServiceQuery = new List<dynamic>
{
    new { ServiceID  = 1, Code = "a" }
};

并获得 WorkOrderID 1,3

Without the ServiceID = 0 requirement it should be a normal left join

根据定义 left outer join 从左侧开始包含 条记录,无论是否有匹配的右侧记录。

由于您的 WorkOrder 位于连接的左侧,因此无论您的 "new requirement".

是什么,您都应该使用正常的左连接