简体   繁体   中英

How to optimise master-slave query with count by max?

I have a query to get games with current number of players for each of game ordered by the measure of what percent of player slots are filled by players.

It goes like this:

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 

And it takes like 4 seconds.

And Explain gives me this mainly:

在此处输入图片说明

How to make it faster?

Try this query. Is it faster?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM