简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM