簡體   English   中英

MySql - 如何查找字段中具有 2 個特定值的記錄,僅此而已

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

我有一個“rel_type”表,有3個字段:id、id_customer、id_type,我必須唯一獲取只有值9和11的id_customer作為id_type。 因此,如果我有記錄有這兩個值但有其他值,則不必提取它們。

我嘗試了各種方法,但沒有結果。

例如:

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

我期望這個輸出:123,這是唯一具有兩個請求值且不超過這些的id_customer。

我會按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

您可以按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