Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to outer join in F# using FLinq?

question pretty much says it all. I have a big flinq query of the following form:

for alias1 in table1 do
    for alias2 in table2 do
        if  alias1.Id = alias2.foreignId

using this form, how can I do a left outer join between these two tables?

like image 377
Ramy Avatar asked Jan 10 '11 19:01

Ramy


People also ask

Can I use (+) for outer join in SQL Server?

The plus sign is Oracle syntax for an outer join. There isn't a minus operator for joins. An outer join means return all rows from one table. Also return the rows from the outer joined where there's a match on the join key.

What is the use of (+) in SQL?

Performing Outer Joins Using the (+) Symbol In practice, the + symbol is placed directly in the conditional statement and on the side of the optional table (the one which is allowed to contain empty or null values within the conditional).

Can you do an outer join in access?

When you want to show all rows from two tables and join them based on common values, you use a full outer join. Access does not explicitly support full outer joins, but you can achieve the same effect by using a union query.


1 Answers

I think you can use the groupJoin function available in the Query module. Here is an example using Northwind with Products as the primary table and Categories as the table with foreign key:

open System.Linq

<@ Query.groupJoin 
     db.Products db.Categories 
     (fun p -> p.CategoryID.Value)
     (fun c -> c.CategoryID)
     (fun p cats ->
        // Here we get a sequence of all categories (which may be empty)
        let cat = cats.FirstOrDefault()
        // 'cat' will be either a Category or 'null' value
        p.ProductName, if cat = null then "(none)" else cat.CategoryName) @>
|> query

There are definitely nicer ways of expressing this using the seq { .. } syntax and by implementing join-like behavior using nested for loops. Unfortunatelly, the quotations to LINQ translator will probably not support these. (Personally, I would prefer writing the code using nested for and using if to check for empty collection).

I was just looking at some improvements in the PowerPack library as part of a contracting work for the F# team, so this will hopefully improve in the future... (but no promises!)

like image 78
Tomas Petricek Avatar answered Oct 02 '22 12:10

Tomas Petricek