为什么`AND f.otherid = 17`条件是JOIN的一部分而不是WHERE子句?

问题描述 投票:0回答:7

我正在尝试将以下 SQL 转换为 LINQ:

SELECT f.value
FROM period as p 
LEFT OUTER JOIN facts AS f
ON p.id = f.periodid AND f.otherid = 17
WHERE p.companyid = 100

我已经看到了左外连接的典型实现(即

into x from y in x.DefaultIfEmpty()
等),但不确定如何引入其他连接条件(
AND f.otherid = 17
)。

为什么

AND f.otherid = 17
条件是 JOIN 的一部分而不是 WHERE 子句?

因为某些行可能不存在

f
,而我仍然希望包含这些行。如果在 JOIN 之后的 WHERE 子句中应用条件 - 那么我不会得到我想要的行为。

不幸的是:

from p in context.Periods
join f in context.Facts on p.id equals f.periodid into fg
from fgi in fg.DefaultIfEmpty()
where p.companyid == 100 && fgi.otherid == 17
select f.value

似乎相当于这个:

SELECT f.value
FROM period as p 
LEFT OUTER JOIN facts AS f
ON p.id = f.periodid 
WHERE p.companyid = 100 AND f.otherid = 17

这不是我想要的。

c# sql linq linq-to-sql outer-join
7个回答
263
投票

致电

DefaultIfEmpty()
之前,您需要先介绍您的加入条件。我只想使用扩展方法语法:

from p in context.Periods
join f in context.Facts on p.id equals f.periodid into fg
from fgi in fg.Where(f => f.otherid == 17).DefaultIfEmpty()
where p.companyid == 100
select f.value

或者你可以使用子查询:

from p in context.Periods
join f in context.Facts on p.id equals f.periodid into fg
from fgi in (from f in fg
             where f.otherid == 17
             select f).DefaultIfEmpty()
where p.companyid == 100
select f.value

33
投票

这也有效,...如果您有多个列连接

from p in context.Periods
join f in context.Facts 
on new {
    id = p.periodid,
    p.otherid
} equals new {
    f.id,
    f.otherid
} into fg
from fgi in fg.DefaultIfEmpty()
where p.companyid == 100
select f.value

19
投票

我知道这是“有点晚了”,但以防万一有人需要在LINQ方法语法中执行此操作(这就是我最初找到这篇文章的原因),这将是如何做到这一点:

var results = context.Periods
    .GroupJoin(
        context.Facts,
        period => period.id,
        fk => fk.periodid,
        (period, fact) => fact.Where(f => f.otherid == 17)
                              .Select(fact.Value)
                              .DefaultIfEmpty()
    )
    .Where(period.companyid==100)
    .SelectMany(fact=>fact).ToList();

5
投票

另一个有效的选项是将联接分散到多个 LINQ 子句,如下所示:

public static IEnumerable<Announcementboard> GetSiteContent(string pageName, DateTime date)
{
    IEnumerable<Announcementboard> content = null;
    IEnumerable<Announcementboard> addMoreContent = null;
        try
        {
            content = from c in DB.Announcementboards
              // Can be displayed beginning on this date
              where c.Displayondate > date.AddDays(-1)
              // Doesn't Expire or Expires at future date
              && (c.Displaythrudate == null || c.Displaythrudate > date)
              // Content is NOT draft, and IS published
              && c.Isdraft == "N" && c.Publishedon != null
              orderby c.Sortorder ascending, c.Heading ascending
              select c;

            // Get the content specific to page names
            if (!string.IsNullOrEmpty(pageName))
            {
              addMoreContent = from c in content
                  join p in DB.Announceonpages on c.Announcementid equals p.Announcementid
                  join s in DB.Apppagenames on p.Apppagenameid equals s.Apppagenameid
                  where s.Apppageref.ToLower() == pageName.ToLower()
                  select c;
            }

            // Add the specified content using UNION
            content = content.Union(addMoreContent);

            // Exclude the duplicates using DISTINCT
            content = content.Distinct();

            return content;
        }
    catch (MyLovelyException ex)
    {
        // Add your exception handling here
        throw ex;
    }
}

1
投票

可以使用复合连接键编写。另外,如果需要从左侧和右侧选择属性,LINQ 可以写成

var result = context.Periods
    .Where(p => p.companyid == 100)
    .GroupJoin(
        context.Facts,
        p => new {p.id, otherid = 17},
        f => new {id = f.periodid, f.otherid},
        (p, f) => new {p, f})
    .SelectMany(
        pf => pf.f.DefaultIfEmpty(),
        (pf, f) => new MyJoinEntity
        {
            Id = pf.p.id,
            Value = f.value,
            // and so on...
        });

-1
投票

虽然我下面的回答并没有直接回答这个问题,但我相信它提供了读者可能会发现有价值的核心问题的替代方案。

我最终在这个线程和其他线程中寻找与我编写的简单自连接 SQL 等效的 EF。我在项目中包含了实体框架,以使我的数据库交互更容易,但必须使用“GroupJoin”、“SelectMany”和“DefaultIfEmpty”就像必须翻译成另一种语言一样。

此外,我与一位擅长 SQL 但 C# 技能有限的工程师一起工作。所以我想要一个他们可以阅读的解决方案。

对我有用的解决方案是:

context.Database.SqlQuery<Class>

这允许执行 SQL 命令并在类型化对象中返回结果。只要返回的列名称与给定类的属性名称匹配即可。例如:

 public class MeasurementEvent
{
    public int ID { get; set; }
    public string JobAssemID { get; set; }
    public DateTime? InspDate { get; set; }


}

var list = context.Database.SqlQuery<MeasurementEvent>(@"
                Select op.umeMeasurementEventID as ID, op.umeJobID+'.'+Cast(op.umeAssemblyID as varchar) as JobAssemID ,  insp.umeCreatedDate as InspDate 
                from uMeasurementEvents as op 
                    left JOIN   uMeasurementEvents as insp on op.umeJobID = insp.umeJobID and op.umeAssemblyID = insp.umeAssemblyID and insp.umeInstanceId = 1 and insp.umeIsInspector = 1
                  where  op.umeInstanceId = 1  and op.umeIsInspector = 0")
            .ToList();

-3
投票

在我看来,在尝试翻译 SQL 代码之前考虑对 SQL 代码进行一些重写是有价值的。

就个人而言,我会将这样的查询编写为联合(尽管我会完全避免空值!):

SELECT f.value
  FROM period as p JOIN facts AS f ON p.id = f.periodid
WHERE p.companyid = 100
      AND f.otherid = 17
UNION
SELECT NULL AS value
  FROM period as p
WHERE p.companyid = 100
      AND NOT EXISTS ( 
                      SELECT * 
                        FROM facts AS f
                       WHERE p.id = f.periodid
                             AND f.otherid = 17
                     );

所以我想我同意@MAbraham1的回答的精神(尽管他们的代码似乎与问题无关)。

但是,查询似乎明确设计为生成包含重复行的单列结果——实际上是重复的空值!很难不得出这样的结论:这种方法是有缺陷的。

© www.soinside.com 2019 - 2024. All rights reserved.