如何通过max?来优化主从查询?

时间:2013-01-10 13:36:09

标签: mysql sql

我有一个查询,通过衡量玩家填充的玩家位数的百分比来获得每个游戏的当前玩家数量的游戏。

它是这样的:

SELECT 
  g.* , COUNT( p.ID ) NUM_OF_PLAYERS 
FROM 
  games g, 
  players p
WHERE  
  g.ID = p.GAME_ID 
GROUP BY 
  g.ID 
ORDER BY 
  COUNT( p.ID ) / g.MAX_NUM_OF_PLAYERS DESC 

需要4秒钟。

而Explain主要给了我这个:

enter image description here

如何加快速度?

1 个答案:

答案 0 :(得分:1)

尝试此查询。它更快吗?

select g.*,p.NUM_OF_PLAYERS NUM_OF_PLAYERS 
from games g
left join 
(
select GAME_ID, COUNT( ID ) NUM_OF_PLAYERS 
  from players group by GAME_ID
) p on (g.ID = p.GAME_ID)

ORDER BY 
  p.NUM_OF_PLAYERS/g.MAX_NUM_OF_PLAYERS DESC