MySql While循环花费太长时间查询

时间:2018-06-22 17:42:41

标签: php mysql

只是想知道是否有更快的方法来运行此查询?我的“结果”表中有超过25万行。该代码在表格中搜索教练进行的所有不同类型的比赛。它查看教练在种族类型中进行了多少场比赛。然后看一下他/她赢得了许多比赛。希望这是足够的信息。感谢您的关注。

echo "<div style='text-align:center;'>";
echo "<table id='main_table'>";  
echo "<tr ><td align = center colspan = 4>".$trainer."</td></tr>";  
$result = mysqli_query($db,"SELECT 
DISTINCT RaceType AS racetype 
FROM results 
WHERE trainer = '$trainer' ORDER BY RaceType ASC");  //placing_numerical,
while($row = mysqli_fetch_array( $result ))         
{
    echo "<tr>";
    echo "<td>";
    echo $row['racetype'];      
    echo "</td>";   
    echo "<td>";
    $result_horse = mysqli_query($db,"
    SELECT 
    COUNT(id) AS result_run 
    FROM results 
    WHERE trainer = '$trainer' AND RaceType = '".$row['racetype']."'
    ");  
    $row_horse = mysqli_fetch_array( $result_horse );
    echo $row_horse['result_run'];  
    $a = $row_horse['result_run'];  
    echo "</td>";   
    echo "<td>";    
    $result_horse1 = mysqli_query($db,"
    SELECT 
    COUNT(id) AS result_win 
    FROM results 
    WHERE trainer = '$trainer' AND RaceType = '".$row['racetype']."' AND placing_numerical = '1'
    ");  
    $row_horse1 = mysqli_fetch_array( $result_horse1 );
    echo $row_horse1['result_win'];
    $b = $row_horse1['result_win']; 
    echo "</td>";   
    echo "<td>";
    $percent = ($b / $a ) * 100;
    $percent = sprintf('%0.0f', $percent);
    echo $percent."%";
    echo "</td>";   
    echo "</tr>";
}   
echo "</table>";

1 个答案:

答案 0 :(得分:0)

这里有两个建议可以检查:-

  1. 对于row_horse和row_horse1,请使用“ mysqli_fetch_assoc”而不是“ mysqli_fetch_array”。

  2. 尝试编写一个包含所有三个查询的查询,这将为您节省更多的时间。