簡體   English   中英

MySQL 查詢用於選擇具有列中所有可能值的不同行

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

這是我的名為“test_tbl”的數據庫表:

ID 類型
1 一個
1
1 C
1 D
2 一個
2
2 C
2 D
3 一個
3
4 一個
4 D

這里每個“id”最多可以有 4 個可能的值(A、B、C、D)用於“類型”列。 我想找出那些在“類型”列中沒有所有四個值的 id。 所以我預期的 output 應該是 ids (3,4)。 我試過如下:

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');

但這給 output 表中的所有 id。

使用聚合:

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

如果可以有 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