Correlated exists sub query predicates

Posts   
 
    
jsmith
User
Posts: 1
Joined: 19-Jul-2005
# Posted on: 19-Jul-2005 05:29:51   

Is there a better way to do a correlated exists sub query?

C# code

PredicateExpression existsSubqueryClause = new PredicateExpression();

existsSubqueryClause.Add(PredicateFactory.CompareValue(
    SubTableFieldIndex.Field1, ComparisonOperator.Equal, "const string"));

existsSubqueryClause.AddWithAnd(
    new FieldCompareExpressionPredicate(
        EntityFieldFactory.Create(ParentTableFieldIndex.ID), null,
        ComparisonOperator.Equal,
        new Expression(EntityFieldFactory.Create(SubTableFieldIndex.ParentTableID))
        )
    );

FilterBucket.PredicateExpression.AddWithAnd(
    new FieldCompareSetPredicate(
        null, null,
        EntityFieldFactory.Create(SubTableFieldIndex.ID), null,
        SetOperator.Exist,
        existsSubqueryClause,
        true)
    );

Resulting MS SQL CODE

SELECT [Schema].[ParentTable].[ID] FROM [Schema].[ParentTable]
WHERE (NOT EXISTS (SELECT [Schema].[SubTable].[ID] FROM [Schema].[SubTable] WHERE ([Schema].[ParentTable].[ID] = [Schema].[SubTable].[ParentTableID])))
Otis avatar
Otis
LLBLGen Pro Team
Posts: 39933
Joined: 17-Aug-2003
# Posted on: 19-Jul-2005 10:30:52   

Couple of options: 1) use a left join between the two tables (parent left join child) and filter on NULL for the child's ParentTableID. All NULL's are valid rows. (and specify allowDuplicates = false) 2) rewrite the query as:


SELECT [Schema].[ParentTable].[ID] 
FROM [Schema].[ParentTable]
WHERE ID NOT IN
(SELECT ParentTableID FROM [Schema].[SubTable])

(imho) which is simpler to form with a fieldcomparesetpredicate.

Frans Bouma | Lead developer LLBLGen Pro