2009-02-24 84 views
0

我有以下表格:SQL選擇這裏重複,但不同的另一列

uid | key | email 
----------------- 
1 | 1 | [email protected] 
2 | 2 | [email protected] 
3 | 3 | [email protected] 
4 | 4 | [email protected] 
5 | 4 | [email protected] 
6 | 4 | [email protected] 
7 | 6 | [email protected] 
8 | 7 | [email protected] 

我想抓住所有具有鮮明的關鍵,但重複的電子郵件行的值,

結果應該看起來像:

uid | key | email 
----------------- 
1 | 1 | [email protected] 
2 | 2 | [email protected] 
3 | 3 | [email protected] 
+0

通過 「另類鑰匙」 嗎你是指那個鍵的表中只有一個出現。在你的例子中,查詢是否返回鍵1,2,3,6和7的行? – JohnFx 2009-02-24 19:01:34

回答

2
SELECT MIN(uid) as uid, key, email 
FROM Keys k INNER JOIN 
    (SELECT email FROM KEYS GROUP by email HAVING COUNT(email) > 1) k2 
    ON k.email = k2.email 
GROUP BY key, email 
HAVING COUNT(key) = 1 
1
SELECT * FROM table 
WHERE email NOT IN 
(
SELECT email 
FROM table GROUP BY email 
HAVING COUNT(email) <= 1) 
AND key IN 
(
SELECT key 
FROM table 
GROUP BY key 
HAVING COUNT(key) = 1 
)