Programing

LINQ to SQL-다중 조인 조건이있는 왼쪽 외부 조인

lottogame 2020. 6. 17. 20:25
반응형

LINQ to SQL-다중 조인 조건이있는 왼쪽 외부 조인


LINQ로 번역하려고하는 다음 SQL이 있습니다.

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 = 17WHERE 절 대신 조건이 JOIN의 일부인 이유는 무엇 입니까? 때문에 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

그것은 내가 추구하는 것이 아닙니다.


에 전화하기 전에 가입 조건을 소개해야합니다 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

... 여러 열 조인이있는 경우에도 작동합니다.

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

나는 " 약간 늦었다 " 것을 알고 있지만 누군가가 LINQ Method 구문 에서이 작업을 수행 해야하는 경우 ( 이것이 처음 에이 게시물을 찾은 이유입니다 ),이 방법은 다음과 같습니다.

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

또 다른 유효한 옵션은 다음과 같이 여러 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;
    }
}

번역을 시도하기 전에 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의 답변 정신에 동의한다고 생각합니다 (코드는 질문과 관련이없는 것으로 보입니다).

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.

참고URL : https://stackoverflow.com/questions/1122942/linq-to-sql-left-outer-join-with-multiple-join-conditions

반응형