我有一張有200萬條記錄的表格。查詢仍然很慢
下面是表
comments
---------
+-------------+---------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+---------------+------+-----+---------+----------------+
| commentid | int(11) | NO | PRI | NULL | auto_increment |
| parentid | int(11) | YES | | 0 | |
| refno | int(11) | YES | | 0 | |
| createdate | int(11) | YES | MUL | 0 | |
| remoteip | varchar(80) | YES | | | |
| fingerprint | varchar(50) | YES | | | |
| locid | int(11) | YES | MUL | 0 | |
| clubid | int(11) | YES | | 0 | |
| profileid | int(11) | YES | MUL | 0 | |
| userid | int(11) | YES | MUL | 0 | |
| global | int(11) | YES | | 0 | |
| official | int(11) | YES | | 0 | |
| legacyuser | int(11) | YES | MUL | 0 | |
| mediaid | int(11) | YES | | 0 | |
| status | int(11) | YES | | 1 | |
| comment | varchar(4000) | YES | | | |
| likes | int(11) | YES | | 0 | |
| dislikes | int(11) | YES | | 0 | |
| import | int(11) | YES | | 0 | |
| author | varchar(50) | YES | | | |
+-------------+---------------+------+-----+---------+----------------+
現在對兩億條記錄此查詢需要6〜7秒:
select * from comments where (locid=2085 or global=1) and status>0 order by createdate desc limit 20;
我決定添加一個索引來LOCID,它仍然在產生的結果6至7秒
我本來可以使用sqlfiddle,但它會不必要的,因爲這個問題的基礎p可以確保性能,我不會將2mil記錄添加到sqlfiddle。
是否有任何策略或實現可以使這個查詢進入3秒範圍?
謝謝!
UPDATE
這是我的解釋顯示錶。
| comments | CREATE TABLE `comments` (
`commentid` int(11) NOT NULL AUTO_INCREMENT,
`parentid` int(11) DEFAULT '0',
`refno` int(11) DEFAULT '0',
`createdate` int(11) DEFAULT '0',
`remoteip` varchar(80) DEFAULT '',
`fingerprint` varchar(50) DEFAULT '',
`locid` int(11) DEFAULT '0',
`clubid` int(11) DEFAULT '0',
`profileid` int(11) DEFAULT '0',
`userid` int(11) DEFAULT '0',
`global` int(11) DEFAULT '0',
`official` int(11) DEFAULT '0',
`legacyuser` int(11) DEFAULT '0',
`mediaid` int(11) DEFAULT '0',
`status` int(11) DEFAULT '1',
`comment` varchar(4000) DEFAULT '',
`likes` int(11) DEFAULT '0',
`dislikes` int(11) DEFAULT '0',
`import` int(11) DEFAULT '0',
`author` varchar(50) DEFAULT '',
PRIMARY KEY (`commentid`),
KEY `comments_locid` (`locid`),
KEY `comments_userid` (`userid`),
KEY `idx_legacyusers` (`legacyuser`),
KEY `profile_index` (`profileid`),
KEY `comments_createdate` (`createdate`),
KEY `compound_for_comments` (`locid`,`global`,`status`),
KEY `global` (`global`),
KEY `status` (`status`)
) ENGINE=InnoDB AUTO_INCREMENT=3848451 DEFAULT CHARSET=latin1
有很好的優化建議(和診斷工具)在那裏值得檢查,請參閱。 https://dev.mysql.com/doc/refman/5.7/en/using-explain.html –
很明顯,在'WHERE'子句中使用的所有列都必須以某種方式進行索引。看看mysql#s'EXPLAIN'特性。它有助於理解正在發生的事情。 – arkascha
K ill look into explain – slicks1