如何使这个个人最好的高分MySQL查询更有效?

时间:2016-10-21 09:41:57

标签: mysql sql database optimization

我有一个游戏排行榜高分榜的数据库,目前有大约30.000个参赛作品,下面的查询会查找特定游戏和玩家的个人最佳高分,但执行时需要 60秒。我认为应该有一个更有效的方法来做到这一点,也许使用复合索引,但那会是哪一个?

SELECT name, score, date, version, mode, attempts, time, id
FROM highscore h1
WHERE score = (
  SELECT MAX( score ) 
  FROM highscore h2
  WHERE name = h1.name && gamename = "asteroids" && name = "bob"
)

我目前有以下索引:

id
score
name
name-gamename (composite)

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:2)

我会使用标准SQL语法编写查询:

SELECT name, score, date, version, mode, attempts, time, id
FROM highscore h1
WHERE score = (SELECT MAX( score ) 
               FROM highscore h2
               WHERE h2.name = h1.name AND h2.gamename = 'asteroids' AND h2.name = 'bob'
              );

为此,您需要复合索引:highscore(name, gamename, score)

如果你只是在寻找一个行(即使有关系),那么这可能会更快一点:

SELECT name, score, date, version, mode, attempts, time, id
FROM highscore h 
WHERE h.gamename = 'asteroids' AND h.name = 'bob'
ORDER BY score DESC
LIMIT 1;

适当的索引是highscore(name, gamename, score)