如何计算数据库中的(重复数)

时间:2015-02-17 18:25:10

标签: php mysql performance levenshtein-distance

我正在编写一些PHP / MySQL来检测过多的网站访问。虽然我觉得很容易检测到,对于任何给定的IP地址,该人在24小时内访问了多少次,因此他们是否超过了访问最大值的某个数字,我正在努力的是一些sql将会挑选出整体趋势 - 每个访问过的IP数量超过了该期间的阈值次数。请考虑以下简化数据库表,我希望能更清楚地解释。

 VisidID        VisitIP      VisitDate
 ---------------------------------- 
    1           n.n.n.01     (yesterday) 
    2           n.n.n.02     (today) 
    3           n.n.n.01     (today) 
    4           n.n.n.03     (today) 
    5           n.n.n.03     (today) 
    6           n.n.n.03     (today) 
    7           n.n.n.04     (today) 
    8           n.n.n.05     (today) 
    9           n.n.n.04     (today) 
    10          n.n.n.06     (today) 
    11          n.n.n.05     (today) 
    12          n.n.n.07     (today)
     ------------------------------------

所以,假设我将允许的最大访问次数阈值设置为2(只是为了让我的示例表保持较小),我从这个表查询中寻找的结果是' 3&#39 ;由于有三个IP地址(n.n.n.03,n.n.n.04和n.n.n.05),今天的访问量均等于或超过了2次访问的访问阈值。

我如何在MySQL查询中捕获它,并且它是一个快速,高效或烦人的查询来运行?

2 个答案:

答案 0 :(得分:4)

使用HAVING子句,此查询将返回计数高于2的那些 -

SELECT `VisitIP`, COUNT(`VisitIP`) AS `CountIP`
FROM `table`
GROUP BY `VisitIP`
HAVING `CountIP` > 2

要计算会议总数,你可以做这样的事情 -

SELECT COUNT(*) AS `TotalOverTwo` FROM
    (SELECT `VisitIP`, COUNT(`VisitIP`) AS `CountIP`
     FROM `table`
     GROUP BY `VisitIP`
     HAVING `CountIP` > 2 
    ) `table`

答案 1 :(得分:-1)

只需编写这个简单的查询,您的问题就会得到解决!

select count(`VisitIP`) as totalVisits from table group by(`VisitDate`) HAVING `totalVisits` > 2;