user1033882 user1033882 - 25 days ago 8
MySQL Question

MySQL - How to count entries in one table based on criteria in another table (except when)

I am trying to do a simple thing and fail...

Basically i want to check how many entries exist in one table based on some values, compared to entries on another table and bring a count of total entries of the first table based on this comparison.

SELECT COUNT(*)
FROM contacts c
INNER JOIN projects p ON p.ContactId = c.ContactId
WHERE c.TypeofContactId = '2'
AND p.CategoryId NOT IN (2,5)


What does this mean? I got 2 tables, one has contacts that i had with customers, and the other is projects created based on those contacts.

The c.TypeofContactId is what type of contact was it (phone, emails, etc)

The p.CategoryId is the type of project created. There can be 50 types.

The projects are 'attached' to contacts based on the ContactId.

I want to count all contacts done for a specific type, but only when the project category was NOT 2 or 5. (so anything else...)

So if it cant find any projects (not 2 or 5 type) for c.type = 2, i should get 0 counts.

What am i doing wrong here?

Thanks.

Answer Source

You can do this:

SELECT SUM(CASE WHEN p.CategoryId NOT IN (2,5) THEN 1 ELSE 0 END) AS TotalCount 
FROM contacts c
INNER JOIN projects p ON p.ContactId = c.ContactId 
WHERE c.TypeofContactId = '2' 

When you put the p.CategoryId NOT IN (2,5) in the where clause, you will get only those rows that match this criteria.