我有顶级服务器网站。我需要为每台服务器计算正常运行时间。
我在数据库中有表统计信息,其中stats所有服务器:
表中有列:
- server_id - 表服务器的列id
- 状态 - 服务器在线/离线。 1 =在线0 =离线
- 在线 - 统计在线玩家
- created_at - 创建记录时的日期。格式:TIMESTAMP
我有cron,它检查数据库中的所有服务器。每10分钟一次检查:
- 如果服务器在线
- 在线玩家数量
cron在stats表中写下这一切。
我想在这里计算正常运行时间服务器:minecraft server page uptime example
我试试这段代码:
SELECT ((COUNT(1) / tmp.total) * 100) AS percentage
FROM stats AS sts
CROSS JOIN (
SELECT COUNT(1) AS total
FROM stats
WHERE DATE(created_at)=CURDATE()
) AS tmp
WHERE DATE(created_at)=CURDATE()
GROUP BY sts.server_id, tmp.total;
但是这个查询性能不好而且没有正确。
我认为,计算服务器正常运行时间的公式是:
uptime : this.server with online = 1 / this.server with online = 0 * 100
我需要获得百分比(正常运行时服务器)在这个例子中如何:
minecraft server page uptime example
如何使用php和mysql查询执行此操作?
答案 0 :(得分:0)
// query all the times a server is offline
$query = "SELECT server_id,COUNT(IF(online=0,1, NULL)),COUNT(*) FROM uptime GROUP BY server_id";
$result = $mysqli->query($query);
// iterate through all server_id's
while($row = $result->fetch_row()){
echo "Server ID: ".$row[0]." -- Uptime: ";
if($row[1] == 0){
$uptime = 100;
}else{
$uptime = $row[1] / $row[2];
$uptime = round(100-($uptime*100),2);
}
echo $uptime."%<br>";
}
<强>输出:强>
Server ID: 1 -- Uptime: 93.25%
Server ID: 2 -- Uptime: 93%
Server ID: 3 -- Uptime: 100%
Server ID: 4 -- Uptime: 100%
Server ID: 5 -- Uptime: 94.08%
Server ID: 6 -- Uptime: 92.75%
Server ID: 7 -- Uptime: 93.83%
Server ID: 8 -- Uptime: 94.58%
Server ID: 9 -- Uptime: 95.25%
Server ID: 10 -- Uptime: 94.42%
用于验证上述示例的测试代码:
$servers = [1,2,3,4,5,6,7,8,9,10]; // create 10 random servers
for($i = 0; $i < 600; $i++){ // create 10 hours of data
foreach($servers as $server){
$players = 0; // no players unless online
$online = rand(0,100); // create artificial 5% down time
if($online > 5 || $server == 3 || $server == 4){
$players = rand(1,50); // choose random player count
$online = 1;
}else{
$online = 0; // server was offline
}
// add status
$query = "INSERT INTO uptime (server_id, status, online) VALUES ($server, $online, $players)";
// echo $mysqli->error;
$mysqli->query($query);
}
}