我有一个users
表和一个emails
表。用户可以收到很多电子邮件。
我想只抓住那些拥有多封电子邮件的用户。以下是我到目前为止的情况:
SELECT Users.name, emails.email
FROM Users
INNER JOIN emails
On Users.id=Emails.user_id
/*specify condition to only grab duplicates here */
答案 0 :(得分:3)
SELECT u.id
FROM Users u
INNER JOIN emails e On u.id = e.user_id
group by u.id
having count(distinct e.email) > 1
使用group by
和having
答案 1 :(得分:0)
您也可以使用CTE:
;WITH CTE AS (
SELECT Users.name, emails.email, ROW_NUMBER() OVER (PARTITION BY emails.email ORDER BY emails.email) AS 'Rank'
FROM Users
INNER JOIN emails
On Users.id=Emails.user_id)
SELECT * FROM CTE WHERE Rank > 1
答案 2 :(得分:0)
您必须计算单个子查询中的电子邮件总数,该子查询返回具有多个电子邮件的用户的user_id。
SELECT users.name, emails.email
FROM users
INNER JOIN emails
ON users.id = emails.user_id
INNER JOIN (
SELECT user_id
FROM emails
GROUP BY user_id
HAVING count(*) > 1
) _cc
ON users.id = _cc.user_id;
更新:如果您只需要user_id而不需要额外的电子邮件,则可以使用:
SELECT DISTINCT(emails.user_id)
FROM users
INNER JOIN emails
ON users.id = emails.user_id
INNER JOIN (
SELECT user_id
FROM emails
GROUP BY user_id
HAVING count(*) > 1
) _cc
ON users.id = _cc.user_id;
假设我们有以下数据:
USERS
id name
1 A
2 B
3 C
4 D
5 E
EMAILS
id user_id email
1 1 email 1
2 1 email 2
3 2 email 3
4 2 email 2
5 3 email 5
因此,使用上述数据,两个查询的结果将是:
QUERY 1
name email
A email 1
A email 2
B email 3
B email 4
QUERY 2
user_id
1
2
答案 3 :(得分:0)
试试这个。您正在通过电子邮件进行分组,并显示那些有计数> 1
SELECT Users.name, emails.email
FROM Users
INNER JOIN emails
On Users.id=Emails.user_id
GROUP BY emails.email HAVING COUNT(*) > 1