简体   繁体   English

MySQL-如何根据另一个表中的条件对一个表中的条目进行计数(时间除外)

[英]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. 我有2个表,一个表有我与客户的联系方式,另一个表是基于这些联系方式创建的项目。

The c.TypeofContactId is what type of contact was it (phone, emails, etc) c.TypeofContactId是联系人的类型(电话,电子邮件等)

The p.CategoryId is the type of project created. p.CategoryId是创建的项目的类型。 There can be 50 types. 可以有50种类型。

The projects are 'attached' to contacts based on the ContactId . 这些项目基于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...) 我只想计算针对特定类型完成的所有联系人,但仅当项目类别不是2或5时才可以。

So if it cant find any projects (not 2 or 5 type) for c.type = 2, i should get 0 counts. 因此,如果它找不到c.type = 2的任何项目(不是2或5类型),我应该得到0个计数。

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. 当将p.CategoryId NOT IN (2,5)放在where子句中时,您将仅获得符合该条件的那些行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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