2017-06-29 91 views
1

請問有人可以幫我解釋一下可能的簡單查詢嗎?在映射表中只選擇一條記錄的查詢

我們有兩個表結構如下。

Customer表:

+----+-----------+ 
| id | name | 
+----+-----------+ 
| 1 | customer1 | 
| 2 | customer2 | 
| 3 | customer3 | 
+----+-----------+ 

Customer role映射表:

+-------------+-----------------+ 
| customer_id | customerRole_id | 
+-------------+-----------------+ 
|   1 |    1 | 
|   1 |    2 | 
|   2 |    1 | 
|   3 |    1 | 
|   4 |    1 | 
|   5 |    1 | 
+-------------+-----------------+ 

我想與角色ID僅1不與角色ID爲1,2,選擇客戶

所以,這種情況下,它將是客戶ID 2,3,4 & 5.忽略1,因爲它有多個角色。

有沒有一個簡單的查詢來做到這一點?

非常感謝,提供任何幫助。

回答

2

嗯,有幾種方法可以做到這一點。

select c.* 
from customers c 
where exists (select 1 from mapping m where m.customerid = c.id and m.role = 1) and 
     not exists (select 1 from mapping m where m.customerid = c.id and m.role <> 1); 

如果你只是想客戶ID,一個簡單的也許是版本:

select customerid 
from mapping 
group by customerid 
having min(role) = 1 and max(role) = 1; 

此解決方案假定role從未NULL

+0

非常感謝,對於如此快速的反應 - 我會試試這個。 – user8232137

+0

第二種解決方案非常適合我需要:-)謝謝! – user8232137

相關問題