我需要根据指定的百分比将流量分成多个来源。我想我需要一个这样的日志表:
表:
+--------+------+----------------------+
| Source | hits | allocated percentage |
+--------+------+----------------------+
| path1 | 50 | 50 |
| path2 | 40 | 40 |
| path3 | 10 | 10 |
+--------+------+----------------------+
我认为逻辑需要遍历所有路径并计算当前百分比,然后确定哪一个离“分配的百分比”最远,然后更新表hits=hits+1
。我在上一个比较部分遇到了麻烦。
$overall_hits = $db->getall('Select sum(total_hits) from table');
$source = $db->getall('Select * from table');
foreach($source as $row){
$current_percentage = ($row['total_hits']/$overall_hits)*100;
//how should I compare? what if they are equal?
if($current_percentage < $row['allocated_percentaged'])
{
$chosen_path = $row['source'];
$db->sql("Update table set total_hits=total_hits+1 where source='".$chosen_path."'");
break;
}else{
continue;
}
}
我是否在正确的轨道上?
答案 0 :(得分:0)
假设我理解你要做的事情,你可以在SQL中进行所有逻辑检查。
以下列数据为例:
CREATE TABLE t (
source TEXT,
hits INT,
percentage INT
);
INSERT INTO t (source, hits, percentage)
VALUES
('path1', 41, 50),
('path2', 27, 40),
('path3', 3, 10)
您可以简单地对整个表运行查询,以计算每个路径的百分比:
SELECT
source,
hits,
percentage,
(hits / percentage) * 100
AS current
FROM t
ORDER BY current ASC;
这会给你以下结果
SOURCE HITS PERCENTAGE CURRENT
path1 3 10 30
path2 27 40 67.5
path3 41 50 82
然后,您只需将LIMIT 1
添加到查询的末尾,即可获得1个结果。这将为您提供hits : allocated
比率最低的路径。
SOURCE HITS PERCENTAGE CURRENT
path1 3 10 30
您可以在SQLFiddle here上看到它。