LINQ to SQL -左外连接具有多个连接条件

时间:2022-12-13 22:58:31

I have the following SQL, which I am trying to translate to LINQ:

我有下面的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

I have seen the typical implementation of the left outer join (ie. into x from y in x.DefaultIfEmpty() etc.) but am unsure how to introduce the other join condition (AND f.otherid = 17)

我已经看到了左外连接(即左外连接)的典型实现。在x. defaultifempty()等中从y到x,但是我不确定如何引入另一个连接条件(和f)。otherid = 17)

EDIT

编辑

Why is the AND f.otherid = 17 condition part of the JOIN instead of in the WHERE clause? Because f may not exist for some rows and I still want these rows to be included. If the condition is applied in the WHERE clause, after the JOIN - then I don't get the behaviour I want.

为什么是和f。otherid = 17条件连接部分而不是WHERE子句?因为对于某些行,f可能不存在,我仍然希望包含这些行。如果条件应用在WHERE子句中,在JOIN之后——那么我不会得到我想要的行为。

Unfortunately this:

不幸的是这样的:

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

seems to be equivalent to this:

似乎是等价的:

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

which is not quite what I'm after.

这不是我想要的。

5 个解决方案

#1


211  

You need to introduce your join condition before calling DefaultIfEmpty(). I would just use extension method syntax:

在调用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

Or you could use a subquery:

或者你可以使用子查询:

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

#2


24  

this works too, ...if you have multiple column joins

这工作太…如果有多个列连接

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

#3


7  

I know it's "a bit late" but just in case if anybody needs to do this in LINQ Method syntax (which is why I found this post initially), this would be how to do that:

我知道有点晚了,但如果有人需要用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();

#4


5  

Another valid option is to spread the joins across multiple LINQ clauses, as follows:

另一个有效的选择是跨多个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;
            }

            //CROSS-JOIN this content
            content = content.Union(addMoreContent);

            //Exclude dupes - effectively OUTER JOIN
            content = content.Distinct();

            return content;
        }
    catch (MyLovelyException ex)
    {
        throw ex;
    }
}

#5


-1  

It seems to me there is value in considering some rewrites to your SQL code before attempting to translate it.

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

Personally, I'd write such a query as a union (although I'd avoid nulls entirely!):

就我个人而言,我将编写这样一个查询作为一个union(尽管我将完全避免nulls !)

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
                     );

So I guess I agree with the spirit of @MAbraham1's answer (though their code seems to be unrelated to the question).

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

However, it seems the query is expressly designed to produce a single column result comprising duplicate rows -- indeed duplicate nulls! It's hard not to come to the conclusion that this approach is flawed.

但是,看起来这个查询被明确地设计为生成一个包含重复行的列结果——实际上是重复的null !很难不得出这样的结论:这种方法是有缺陷的。

#1


211  

You need to introduce your join condition before calling DefaultIfEmpty(). I would just use extension method syntax:

在调用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

Or you could use a subquery:

或者你可以使用子查询:

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

#2


24  

this works too, ...if you have multiple column joins

这工作太…如果有多个列连接

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

#3


7  

I know it's "a bit late" but just in case if anybody needs to do this in LINQ Method syntax (which is why I found this post initially), this would be how to do that:

我知道有点晚了,但如果有人需要用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();

#4


5  

Another valid option is to spread the joins across multiple LINQ clauses, as follows:

另一个有效的选择是跨多个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;
            }

            //CROSS-JOIN this content
            content = content.Union(addMoreContent);

            //Exclude dupes - effectively OUTER JOIN
            content = content.Distinct();

            return content;
        }
    catch (MyLovelyException ex)
    {
        throw ex;
    }
}

#5


-1  

It seems to me there is value in considering some rewrites to your SQL code before attempting to translate it.

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

Personally, I'd write such a query as a union (although I'd avoid nulls entirely!):

就我个人而言,我将编写这样一个查询作为一个union(尽管我将完全避免nulls !)

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
                     );

So I guess I agree with the spirit of @MAbraham1's answer (though their code seems to be unrelated to the question).

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

However, it seems the query is expressly designed to produce a single column result comprising duplicate rows -- indeed duplicate nulls! It's hard not to come to the conclusion that this approach is flawed.

但是,看起来这个查询被明确地设计为生成一个包含重复行的列结果——实际上是重复的null !很难不得出这样的结论:这种方法是有缺陷的。