Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why is GroupJoin not left outer join?

Tags:

c#

linq

The GroupJoin method has no direct equivalent in relational database terms, but it implements a superset of inner joins and left outer joins. A left outer join is a join that returns each element of the first (left) data source, even if it has no correlated elements in the other data source.

I think the GroupJoin is a equivalent of left join. Because all element of outer will be returned with a collection of matched items in inner. if no matched item is found in inner, an empty collection will be paired with the element in outer.

But why does msdn say that?

I have read source code of GroupJoin and Join. MarcinJuraszek supply a example. but I think we can use following code.

Users.GroupJoin(Cars,user=>id,Car=>userId,(user,cars)=>
if(cars.count==0)
{
//John -- NULL
}
else
{
//Ted  -- [ 2, 3 ]
}
return result;
);

original logic for GroupJoin:

Lookup<TKey, TInner> lookup = Lookup<TKey, TInner>.CreateForJoin(inner, innerKeySelector, comparer);
foreach (TOuter current in outer)
{
    yield return resultSelector(current, lookup[outerKeySelector(current)]);
}

we can also rewrite a LeftJoin:

Lookup<TKey, TInner> lookup = Lookup<TKey, TInner>.CreateForJoin(inner, innerKeySelector, 
foreach (TOuter current in outer)
{
    yield return resultSelector(current, lookup[outerKeySelector(current)].DefaultIfEmpty());
}
like image 562
Vince Avatar asked Dec 20 '22 02:12

Vince


1 Answers

Consider following situation:

TableA - Users

id -- name
1  -- Tom
2  -- John
3  -- Ted

TableB - Cars

id -- userId
1  -- 1
2  -- 3
3  -- 3

Standard LEFT JOIN for user name and car id would return:

name -- carId
Tom  -- 1
John -- NULL
Ted  -- 2
Ted  -- 3

Using GroupJoin you'll get:

name -- carId
Tom  -- [ 1 ]
John -- [ ]
Ted  -- [ 2, 3 ]

See the difference?

In SQL the left side idem is shown as many times as many right items matching JOINcondition exist.

On GroupJoin you'll get left side item once and a collection of right side items matching JOINcondition.

like image 155
MarcinJuraszek Avatar answered Dec 22 '22 15:12

MarcinJuraszek