Can you a use QueryExpression to get the records from table1 without a matching record in table2?

256 views Asked by At

In SQL this brings back all the rows which have a matching record in both tables.

SELECT * 
FROM table1 
INNER JOIN table2 ON table2.t2ID = table1.t1ID
WHERE ANumberField = '2'`

I've got a QueryExpression that returns this.

QueryExpression theQuery = new QueryExpression("table1");
theQuery.ColumnSet.AddColumns("t1ID ");

LinkEntity link = theQuery.AddLink("table2", "t1ID ", "t2ID");
link.Columns.AddColumn("t2ID");

FilterExpression theFilter = link.LinkCriteria.AddFilter(LogicalOperator.Or);
theFilter.Conditions.Add(new ConditionExpression("ANumberField", ConditionOperator.Equal, 2));

Is there a way to invert that QueryExpression to do the equivalent of these?

This T-SQL gets records with a link, but not the criteria I need.

SELECT * 
FROM table1 
INNER JOIN table2 ON table2.t2ID = table1.t1ID 
WHERE NOT ANumberField = '2'

This gets records with no link between the two tables.

SELECT * 
FROM table1 
WHERE t1ID NOT IN (SELECT t2ID FROM table2)
1

There are 1 answers

0
AnkUser On

I tried what you wish to achieve, I used account and contact entity for my testing criteria is address1_line1 is not null. I got correct result as expeczed.

SELECT name,
       account.accountid,
       contact.contactid,
       contact.parentcustomerid,
       contact.fullname,
       contact.address1_line1
FROM   account
       INNER JOIN
       contact AS contact
       ON contact.parentcustomerid = account.accountid
          AND contact.address1_line1 IS NOT NULL;

    // Instantiate QueryExpression query
    var query = new QueryExpression("account");
   query.ColumnSet.AddColumns("account.accountid"); 
    // Add link-entity query_contact
    var query_contact = query.AddLink("contact", "accountid", "parentcustomerid");
    query_contact.ColumnSet.AddColumns("contact.contactid",
       "contact.parentcustomerid","contact.fullname",      "contact.address1_line1");
    // Define filter query_contact.LinkCriteria
    query_contact.LinkCriteria.AddCondition("address1_line1", ConditionOperator.NotNull);