0

假设我们有一个名为的表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

有什么建议如何在不杀死 MySQL 的情况下将表加入自身并获得所需的输出以获取 100 万条记录?

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

4

3 回答 3

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;
于 2013-04-18T09:49:38.287 回答
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;
于 2013-04-18T10:10:29.120 回答
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
于 2013-04-18T09:52:36.783 回答