真的很大的SELECT查询

时间:2012-06-18 16:22:00

标签: php mysql sql optimization

我想询问是否有更快的方法来进行此查询?实际上完成需要大约100秒。我在表中有大约10 000 000(1 GB)行。这是统计信息生成脚本。

这是查询:

  $results=mysql_query("SELECT * FROM hawkeye WHERE player_id='".$playerID."'") or die("MYSQL ERROR: ".mysql_error());

然后是php代码:

  $row = mysql_fetch_array($results)
  if($row["action"] == 4){$commandcount++;}
  else if($row["action"] == 3){$chatcount++;}
  else if($row["action"] == 1){$placedcount++;}
  else if($row["action"] == 0){$breakcount++;}
  else if($row["action"] == 5){$joincount++;}
  else if($row["action"] == 6){$quitcount++;}
  else if($row["action"] == 7){$qteleportcount++;}
  else if($row["action"] == 12){$pvpdeathcount++;}
  else if($row["action"] == 21){$mobkillcount++;}
  else if($row["action"] == 22){$otherdeathcount++;}
  else {}

感谢您的回答!

5 个答案:

答案 0 :(得分:11)

使用MYSQL为您做数学运算。它比PHP更快:

SELECT COUNT(*) AS action_count
     , action
FROM hawkeye 
WHERE player_id='".$playerID."'"
GROUP BY action

while ($row = mysql_fetch_assoc($result))
{
    echo $row['action'] . ': ' . $row['action_count'] . "<br>" . PHP_EOL;
}

答案 1 :(得分:2)

怎么样?
SELECT action, count(*) FROM hawkeye WHERE player_id='$playerID' GROUP BY action

因此,您只会按操作类型循环一次,而不是每操作

一次

答案 2 :(得分:1)

看来你正在尝试做一些计算。尝试进行聚合和/或使用分析数据库,如infobright,将聚合存储在内存中。避免执行SELECT *并执行实际的SELECT column1,column2。主要是阅读做SUM,COUNT Group BY和Order By等聚合。

答案 3 :(得分:1)

$results=mysql_query("SELECT action, count(*) as `cnt` FROM hawkeye WHERE player_id='".$playerID."' GROUP BY action") or die("MYSQL ERROR: ".mysql_error());

while ($row = mysql_fetch_array($results)) {
  if($row["action"] == 4){$commandcount=$row["cnt"];}
  else if($row["action"] == 3){$chatcount=$row["cnt"];}
  else if($row["action"] == 1){$placedcount=$row["cnt"];}
  else if($row["action"] == 0){$breakcount=$row["cnt"];}
  else if($row["action"] == 5){$joincount=$row["cnt"];}
  else if($row["action"] == 6){$quitcount=$row["cnt"];}
  else if($row["action"] == 7){$qteleportcount=$row["cnt"];}
  else if($row["action"] == 12){$pvpdeathcount=$row["cnt"];}
  else if($row["action"] == 21){$mobkillcount=$row["cnt"];}
  else if($row["action"] == 22){$otherdeathcount=$row["cnt"];}
  else {}
}

答案 4 :(得分:1)

为按player_id索引的鹰眼表添加索引,并遵循John Conde的建议。