stanke
stanke

Reputation: 286

SQL queries with different results

I have two tables that I try to join over one field and it gives me different results in two queries that should give same results. Queries are:

SELECT * FROM tblCustomer tca
WHERE tca.PhoneNumber IN(
    SELECT ts.SubscriptionNumber FROM sub.tblSubscription ts
    WHERE ts.ServiceTypeID=4
    AND ts.SourceID=-1
)

and

SELECT tca.*
FROM   sub.tblSubscription ts
       inner JOIN tblCustomer tca
            ON  ts.SubscriptionNumber = tca.PhoneNumber
WHERE  ts.ServiceTypeID = 4
       AND ts.SourceID = -1

How is this possible?

Upvotes: 1

Views: 106

Answers (1)

FarligOpptreden
FarligOpptreden

Reputation: 5043

I'm assuming a customer can have multiple subscriptions, right? Let's assume you have 5 customers, each with 2 subscriptions...

When doing a SELECT ... FROM Customer WHERE IN (Subscription), you will receive 5 customer records, because each of those 5 customers are in fact in the subscription table, even though the subscription table will have 10 records. You are inherently asking the database for the data from one table, where the value of one of it's fields exists in another table. So it will only return the distinct records in the FROM table, irrespective of the amount of data in the WHERE IN table.

On the other hand, INNER JOINing the Customer table with the subscription table will return 5 customers x 2 subscriptions each = 10 records. By JOINing the tables you are asking the database for ALL the data in each table, where the data is matched up against specific fields.

So yes, the 2 queries will definitely give you different results.

Upvotes: 3

Related Questions