簡體   English   中英

提高Mysql查詢性能

[英]Improve Mysql query performance

我有這個高分表

CREATE TABLE IF NOT EXISTS高分則CREATE TABLE IF NOT EXISTS ( lid int(11) NOT NULL,用戶名varchar(50) NOT NULL, userid int(6) NOT NULL,得分int(16) NOT NULL,日期的timestamp NOT NULL default CURRENT_TIMESTAMP, PRIMARY KEY ( lid , username ), KEY score ( lid , score ) ) ENGINE=MyISAM DEFAULT CHARSET=latin1;

它有超過200萬行。 當我運行以下查詢時,大約需要4.5秒。 我希望這里的人對如何通過更改查詢,添加/修改索引或更改存儲引擎來提高速度提供一些建議?

在h.lid = t.lid上選擇h.userid,h.username AS用戶,count(h.username)AS分數來自高分數h INNER JOIN(選擇lid,min(score)AS maxscore從highscores按蓋子分組) h.score = t.maxscore按h.username分組ORDER BY scorecount DESC

以下是要求的解釋: 說明

這是您的查詢:

SELECT h.userid, h.username AS user, count(h.username) AS scorecount
FROM highscores h INNER JOIN
     (select lid, min(score) AS maxscore
      FROM highscores
      group by lid
     ) t
     on h.lid = t.lid and h.score = t.maxscore
group by h.username
ORDER BY scorecount DESC;

這似乎正在回答以下問題:“用戶在表中獲得最高(或最低)分數的次數是多少?”。 這表明您可以將查詢重寫為:

select hs.userid, hs.username, count(*) as scorecount
from highscores hs
where not exists (select 1 from highscores hs2 where hs2.lid = hs.lid and hs2.score > hs.score)
group by hs.userid, hs.username
order by scorecount desc;

您現有的索引應該可以很好地解決此問題。 userid, username的索引將對某些數據庫引擎有所幫助,但我認為MySQL不會利用它。

我最終要做的是緩存查詢,每10分鍾更新一次。 可能有更好的解決方案,但我無法使查詢更快。

先生,我不認為調整您的查詢是您正確的解決方案。 您只是說您在該分數表中有200萬行。 您能想象每執行一次查詢要檢查每行的單元格/行多長時間嗎?

您需要的是數據庫規范化和設計表的正確方法

http://en.wikipedia.org/wiki/Database_normalization

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM