简体   繁体   English

MySQL 查询用于选择具有列中所有可能值的不同行

[英]MySQL query for selecting distinct rows with all possible values in a column

Here's my DB table named 'test_tbl':这是我的名为“test_tbl”的数据库表:

id ID type类型
1 1 A一个
1 1 B
1 1 C C
1 1 D D
2 2 A一个
2 2 B
2 2 C C
2 2 D D
3 3 A一个
3 3 B
4 4 A一个
4 4 D D

Here every 'id' can have at most 4 possible values (A,B,C,D) for 'type' column.这里每个“id”最多可以有 4 个可能的值(A、B、C、D)用于“类型”列。 I want to find out those ids who don't have all four values in 'type' column.我想找出那些在“类型”列中没有所有四个值的 id。 So my expected output should be ids (3,4).所以我预期的 output 应该是 ids (3,4)。 I have tried as following:我试过如下:

select DISTINCT id
from test_tbl
where id NOT IN 
    (SELECT id FROM test_tbl 
    where
    type='A' and type='B' and type='C' and type='D');

But this is giving output all the ids from table.但这给 output 表中的所有 id。

Use aggregation:使用聚合:

select id
from test_tbl
group by id
having count(distinct type) <> 4;

If you can have types other than A, B, C, and D, then add:如果可以有 A、B、C 和 D 以外的类型,则添加:

where type in ('A', 'B', 'C', 'D')

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

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