简体   繁体   English

MySql - 如何查找字段中具有 2 个特定值的记录,仅此而已

[英]MySql - how to find records that have 2 specific values ​in a field, and no more

I have a "rel_type" table, with 3 fields: id, id_customer, id_type, I must uniquely get the id_customer that have only values ​​9 and 11 as id_type.我有一个“rel_type”表,有3个字段:id、id_customer、id_type,我必须唯一获取只有值9和11的id_customer作为id_type。 So if I have recods that have these two values ​​but have others, they don't have to be extracted.因此,如果我有记录有这两个值但有其他值,则不必提取它们。

I have tried in various ways but without results.我尝试了各种方法,但没有结果。

For example:例如:

id | id_customer | id_type
--------------------------
1  |     123     |    11
2  |     345     |     9
3  |     123     |     9
4  |     788     |     5
5  |     788     |    11
6  |     788     |     9
7  |     788     |     4

I expect this output: 123, which is the only id_customer that has the two requested values ​​and no more than these.我期望这个输出:123,这是唯一具有两个请求值且不超过这些的id_customer。

I'd group by the id_customer , and then apply two conditions - that the total count is 2 and that the count of records with 9 or 11 is also 2:我会按id_customer ,然后应用两个条件 - 总计数为 2 并且具有 9 或 11 的记录计数也是 2:

SELECT id_customer
FROM   mytable
GROUP BY id_customer
HAVING   COUNT(*) = 2 AND
         COUNT(CASE WHEN id_type IN (9, 11) THEN 1 END) = 2

You can group by id_customer :您可以按id_customer

select id_customer
from tablename
group by id_customer
having min(id_type) = 9 and max(id_type) = 11 and count(distinct id_type) = 2

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

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