MySQL - 至少发生3次

时间:2018-01-12 11:00:11

标签: mysql sql database

我有这个查询,工作正常:

SELECT t1.*, t2.ip as ip 
FROM table1 t1
INNER JOIN table2 t2 ON ( t2.id = t1.t2id )
ORDER BY t1.timestamp DESC
LIMIT 1000

我想做的是:

1)仅获取相同ip出现至少3次的条目

2)按ip

对条目进行分组

所以结果看起来像这个例子:

IP                  TIMESTAMP
111.111.111.111     1500000000
111.111.111.111     1300000000
111.111.111.111     1100000000
222.222.222.222     1400000000
222.222.222.222     1300000000
222.222.222.222     1200000000

我尝试了很多方法,我相信这个方法最接近, 但结果是0行。

SELECT *, COUNT(DISTINCT ip) FROM ( 
    SELECT t1.*, t2.ip as ip 
    FROM table1 t1
    INNER JOIN table2 t2 ON ( t2.id = t1.t2id )
    ORDER BY t1.timestamp DESC
    LIMIT 1000
) AS tmp_table 
GROUP BY ip
HAVING COUNT(DISTINCT ip) > 2

请有人对此有所了解吗?

4 个答案:

答案 0 :(得分:2)

试试这个:

SELECT t1.*, (SELECT DISTINCT t2.ip FROM t2 WHERE t2.id = t1.t2id)
FROM t1
WHERE
    (SELECT COUNT(*)
    FROM t2
    WHERE t2.id = t1.t2id) >= 3

在评论中导致表格t2导致同一IP的行数更多我改变了我的查询如下:

SELECT t1.*, t2.ip
FROM t1
JOIN t2
    ON t2.id = t1.t2id
WHERE
    (SELECT COUNT(*)
    FROM t2 tt2
    WHERE t2.ip = tt2.ip) >= 3

您可以看到SqlFiddle

答案 1 :(得分:1)

您必须在子查询中使用HAVING

SELECT t1.*, t2.ip as ip 
FROM table1 t1
INNER JOIN table2 t2 ON ( t2.id = t1.t2id ) 
INNER JOIN 
(
    SELECT t2.ip
    FROM table1 t1
    INNER JOIN table1 t2 ON ( t2.id = t2.t2id )
    GROUP BY t2.ip
    HAVING count(ip) > 2
) t ON t2.ip = t.ip

答案 2 :(得分:1)

SELECT *, COUNT(ip) FROM ( 
    SELECT t1.*, t2.ip as ip 
    FROM table1 t1
    INNER JOIN table2 t2 ON ( t2.id = t1.t2id )
    ORDER BY t1.timestamp DESC
    LIMIT 1000
) AS tmp_table 
GROUP BY ip
HAVING COUNT(ip) > 2

删除不同的

答案 3 :(得分:0)

试试这个;

SELECT t2.ip as ip 
FROM table1 t1
INNER JOIN table2 t2 ON ( t2.id = t1.t2id )
where t2.ip IN (SELECT ip FROM ( 
    SELECT t2.ip as ip 
    FROM table1 t1
    INNER JOIN table2 t2 ON ( t2.id = t1.t2id )
    ) AS tmp_table 
    GROUP BY ip
    HAVING COUNT(*) > 2)
ORDER BY t1.timestamp DESC
LIMIT 1000