如何使多个语句循环合而为一? (性能问题/ PHP)

时间:2018-07-10 22:50:41

标签: php mysql

我如何优化以下代码? 我如何将4个循环简化为1个循环,它们几乎总是相同的MySQL语句。只有WHERE中的step值总是不同的。

目前,代码中此部分的加载时间约为5-7秒,这太长了……每个循环都达到最大值。 200-300次通过。

// Tank battles heute MySQL
$tday = array();
$result2 = mysqli_query($db, "SELECT * FROM activity_day_account_vehicles WHERE account_id = '$me_id' AND step = '$step'");
while($row_tday = mysqli_fetch_assoc($result2)) {
    $t_id = $row_tday['tank_id'];
    $tday[$t_id] = $row_tday['statistics_battles'];
}
// Tank battles gestern MySQL
$tday2 = array();
$result3 = mysqli_query($db, "SELECT * FROM activity_day_account_vehicles WHERE account_id = '$me_id' AND step = '$step2'");
while($row_tday2 = mysqli_fetch_assoc($result3)) {
    $t_id = $row_tday2['tank_id'];
    $tday2[$t_id] = $row_tday2['statistics_battles'];
}
// Tank battles Woche MySQL
$tweek = array();
$result4 = mysqli_query($db, "SELECT * FROM activity_day_account_vehicles WHERE account_id = '$me_id' AND step = '$step3'");
$menge2 = mysqli_num_rows($result4);
if ($menge2 === 0) {
    $result4 = mysqli_query($db, "SELECT * FROM activity_day_account_vehicles WHERE account_id = '$me_id' ORDER BY step ASC LIMIT $anzahl2");
}
while($row_tweek = mysqli_fetch_assoc($result4)) {
    $t_id = $row_tweek['tank_id'];
    $tweek[$t_id] = $row_tweek['statistics_battles'];
}
// Tank battles Monat MySQL
$tmonth = array();
$result5 = mysqli_query($db, "SELECT * FROM activity_day_account_vehicles WHERE account_id = '$me_id' AND step = '$step4'");
$menge2 = mysqli_num_rows($result5);
if ($menge2 === 0) {
    $result5 = mysqli_query($db, "SELECT * FROM activity_day_account_vehicles WHERE account_id = '$me_id' ORDER BY step ASC LIMIT $anzahl2");
}
while($row_tmonth = mysqli_fetch_assoc($result5)) {
    $t_id = $row_tmonth['tank_id'];
    $tmonth[$t_id] = $row_tmonth['statistics_battles'];
}

1 个答案:

答案 0 :(得分:0)

在account_id上创建索引并执行以下步骤:

CREATE INDEX activity_day_account_vehicles_001
ON activity_day_account_vehicles (account_id);

CREATE INDEX activity_day_account_vehicles_002
ON activity_day_account_vehicles (step);