Search code examples
f#computation-expressionquery-expressions

query expression self-join


How can I change this query expression's join clause so that I don't have to wrap parent.ID in an option just to join on a candidate child.ParentID which might be None?

query { for parent in d.People do
        join child in d.People on (Some parent.ID = child.ParentID)
        exists (child.Birthdate <= parent.Birthdate) }

Thanks!


Solution

  • You might like this. There may be a more elegant syntax for this approach, and I expect in the end it is not going to perform much differently, if at all, but here it is:

    query { for child in d.People do
            where (child.ParentID.IsSome)
            join parent in d.People on (child.ParentID.Value = parent.ID)
            exists (child.Birthdate <= parent.Birthdate) }
    

    I first came up with this, but I wondered whether it implies calling Value before filtering out the None values:

    query { for parent in d.People do
            join child in d.People on (parent.ID = child.ParentID.Value)
            where (child.ParentID.IsSome)
            exists (child.Birthdate <= parent.Birthdate) }
    

    To keep parent first and also put the child filter before the join condition, you can do a subquery, but that seemed a worse solution, not better. If someone knows a way of doing that without the subquery, please add a comment.