获取表中所有电子邮件地址的所有IP地址

时间:2013-04-18 09:39:15

标签: mysql join group-by

假设我们有一个名为record的表,它有3个字段

id email ip

场合

我们必须找出哪些电子邮件地址使用了超过2个IP地址以及这些IP地址是什么。现在如果它只是COUNT,我们只需使用

SELECT email,COUNT(DISTINCT ip) as C FROM record GROUP BY email HAVING(c>2)

但我还需要看到那些IP地址。所以期望的输出就像

email1@example.com  192.168.0.1
email1@example.com  192.168.0.2
email1@example.com  192.168.0.3
email1@example.com  192.168.0.4
email1@example.com  192.168.0.5

...etc...

email2@example.com  192.168.1.3
email2@example.com  192.168.1.4
email2@example.com  192.168.1.5

如何建议如何将表连接到自身并获得所需的输出而不会杀死100万条记录的MySQL?

注意:请注意,ip存储为INT并被编入索引。我不需要将该ip转换回其字符串表示形式的帮助,对于这个问题的任何实际答案都可以忽略。

3 个答案:

答案 0 :(得分:2)

您的查询将返回电子邮件及其计数,但您还需要列出的IP地址

SELECT 
   a.email, 
   a.ipAddress,
   b.cnt
FROM
   (SELECT 
       email,
       COUNT(DISTINCT ip) as cnt
   FROM 
       record 
   GROUP BY 
       email 
   HAVING(c>2))b
INNER JOIN
   (SELECT 
       DISTINCT *
   FROM
       record) a
ON
   a.email = b.email;

答案 1 :(得分:1)

根据@Meherzad的回复,但返回唯一的IP地址: -

SELECT 
   a.email, 
   a.ipAddress,
   b.cnt
FROM
   (SELECT email, COUNT(DISTINCT ip) as cnt
   FROM record 
   GROUP BY email 
   HAVING(c>2))b
INNER JOIN
   (SELECT DISTINCT email, ip
   FROM record) a
ON
   a.email = b.email;

答案 2 :(得分:0)

如何对查询进行子集化(我猜不会使用MySQL中的视图)

select * from records where email in (
select email 
from records
group by email
having count(email) > 2)

编辑:忘记添加IP的distinct子句,删除IN子句,然后加入小部分电子邮件

select distinct records.email, ip from records
inner join
(select email 
from records
group by email
having count(email) > 2) as subq
ON subq.email = records.email