[英]MySQL query for selecting distinct rows with all possible values in a column
Here's my DB table named 'test_tbl':这是我的名为“test_tbl”的数据库表:
id ![]() |
type![]() |
---|---|
1 ![]() |
A![]() |
1 ![]() |
B![]() |
1 ![]() |
C ![]() |
1 ![]() |
D ![]() |
2 ![]() |
A![]() |
2 ![]() |
B![]() |
2 ![]() |
C ![]() |
2 ![]() |
D ![]() |
3 ![]() |
A![]() |
3 ![]() |
B![]() |
4 ![]() |
A![]() |
4 ![]() |
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.