mysql - 使用 MySQL 计算正常帐户内 IP 地址的变化

标签 mysql

previous question 中真棒amdixon能够提出一个查询来计算 IP 的重复级别。

我已经使用 WHERE earning_account_id = ? 对此进行了调整以查看特定帐户:

SELECT MAX(repeat_factor)
FROM
(
SELECT earning_ip, count(*) / rc.row_count AS repeat_factor
FROM earnings
CROSS JOIN (SELECT count(*) AS row_count FROM earnings WHERE earning_account_id = ?) rc
WHERE earning_account_id = ?
GROUP BY earning_ip
) q

但是,现在我想增加一个额外的安全级别。

我想应用相同类型的查询。但我不想将其限制为 earning_account_id,而是想将其限制为任何看到特定 IP 地址的帐户分组。

如果他们使用多个 alt 帐户,我可以更好地全局检测代理垃圾邮件。

请注意,我将不再使用 WHERE earning_account_id = ?

限制查询

换句话说,如果 ip_address 是“45.55.80.86”

+--------------------+-------------+---------------------------+
| earning_account_id | earning_ip  | select row for repeat_factor query?|
+--------------------+-------------+---------------------------+
|                  1 | 45.55.80.86 | YES                       |
|                  1 | 45.55.80.86 | YES                       |
|                  2 | 1.22.83.65  | NO                        |
|                  2 | 91.15.76.37 | NO                        |
|                  3 | 45.55.80.86 | YES                       |
|                  4 | 61.25.76.37 | YES                       |
|                  4 | 1.22.83.65  | YES                       |
|                  4 | 45.55.80.86 | YES                       |
|                  5 | 61.25.76.37 | NO                        |
+--------------------+-------------+---------------------------+

要返回的值将是此 ip 所有收入的 repeat_factor,但忽略所有从未包含此 ip 地址的帐户

换句话说,我想找出的是:

"how repetitive is this IP address within all accounts, but looking only at the accounts where this IP address has been sighted?"

最佳答案

可以很简单地获取要选择的行:

select e.*
from example e
join 
(select distinct earning_account_id
 from example
 where ip = '45.55.80.86') subq
on e.earning_account_id = subq.earning_account_id;

此时,如果它是一个 SQL Server 数据库,您可以简单地将它捆绑到一个公用表表达式 (CTE) 中,并使用它的别名而不是对 amdixon's query 中表名的两个引用。 .遗憾MySQL doesn't provide such a luxury所以我们仅限于子查询,每个子查询都必须有一个唯一的别名——虽然有点难看,但这样做是可行的:

select max(repeat_factor)
from
(
select ip, count(*) / rc.row_count as repeat_factor
from
(select e.*
 from example e
 join 
 (select distinct earning_account_id
  from example
  where ip = '45.55.80.86') subq
 on e.earning_account_id = subq.earning_account_id) cte1
cross join ( select count(*) as row_count from 
(select e.*
 from example e
 join 
 (select distinct earning_account_id
  from example
  where ip = '45.55.80.86') subq
 on e.earning_account_id = subq.earning_account_id) cte2
) rc
group by ip
) q;

参见 SQL Fiddle Demo

关于mysql - 使用 MySQL 计算正常帐户内 IP 地址的变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34575293/

相关文章:

php - PHP OOP更新记录,但显示错误消息

php - 从 mysql 数据库中读取特定数据

php - 在 phpmyadmin 中截断数据需要什么权限?

mysql - 使用命令行更改mysql用户密码

mysql - mysql删除错误

mysql - 如何在 mysql 中查找特定泰米尔语单词的 unicode 字符

php - 以编程方式同步记录的想法

javascript - 在 PHP 代码中单击链接 javascript 函数调用

MySQL 查询查找每组中重复次数最多的项目

mysql - 如何在Mysql中删除特定分区中的子分区?