2012-02-02 62 views
2

我有如下表格,如果多於一行包含相同的'user_badge_name'和'user_email',則認爲重複。檢索表中的重複項並顯示它們

user_id | user_name | user_badge_name | user_email 
-------------------------------------------------- 
234  | Kylie  | ky001   | [email protected] 
235  | Francois | FR007   | [email protected] 
236  | Maria  | MA300   | [email protected] 
237  | Francine | FR007   | [email protected] 

我需要顯示user_ids和其中「user_badge_name」和「USER_EMAIL」被複制的那些行的用戶名。

我嘗試以下SQL,但它不是返回所有user_ids,只有第一個ID

SELECT user_id, username , COUNT(user_badge_name) AS user_badge_name_Count FROM user GROUP BY user_badge_name HAVING user_badge_name_Count > 1 

任何建議最欣賞

+0

如果目標是防止重複條目,爲什麼表結構允許它們?如果你將'user_email'和'user_badge_name'聲明爲UNIQUE,那麼你將永遠不會遇到這些列中重複的問題。 – 2012-02-02 17:47:44

+0

我正在使用已包含重複項的現有表。我只需要顯示那些重複的內容 – Kim 2012-02-02 17:59:16

回答

3
select a.user_id, a.user_name 
from user as a 
inner join 
(SELECT user_badge_name, user_email 
FROM user 
GROUP BY user_badge_name, user_email 
HAVING count(*)>1 
) as dups 
on a.user_badge_name=dups.user_badge_name and a.user_email=dups.user_email 
order by a.user_badge_name, a.user_email 
1

如果你想看到在同所有用戶ID的行,那麼你可以使用GROUP_CONCAT

SELECT GROUP_CONCAT(user_id) AS user_ids, GROUP_CONCAT(username) AS usernames, COUNT(user_badge_name) AS user_badge_name_Count FROM user GROUP BY user_badge_name HAVING user_badge_name_Count > 1 

這會給你這樣的事情:

user_ids | usernames   | user_badge_name_Count 
----------------------------------------------- 
235,237 | Francois,Francine | 2 
+0

感謝您的「GROUP_CONCAT」建議 – Kim 2012-02-02 17:58:13

相關問題