【发布时间】:2018-01-15 20:31:17
【问题描述】:
我花了 4 个小时在谷歌上搜索并尝试了各种索引、mysqlyog、阅读、搜索等。当我添加 GROUP BY 时,查询从 0.002 秒变为 0.093 秒。这是正常的和可以接受的吗?或者我可以更改索引和/或查询吗?
表:
uniqueid int(11) NO PRI NULL auto_increment
ip varchar(64) YES NULL
lang varchar(16) YES MUL NULL
timestamp int(11) YES MUL NULL
correct decimal(12,2) YES NULL
user varchar(32) YES NULL
timestart int(11) YES NULL
timeend int(11) YES NULL
speaker varchar(64) YES NULL
postedAnswer int(32) YES NULL
correctAnswerINT int(32) YES NULL
查询:
SELECT
SQL_NO_CACHE
user,
lang,
COUNT(*) AS total,
SUM(correct) AS correct,
ROUND(SUM(correct) / COUNT(*) * 100) AS score,
TIMESTAMP
FROM
maths_score
WHERE TIMESTAMP > 1
AND lang = 'es'
GROUP BY USER
ORDER BY (
(SUM(correct) / COUNT(*) * 100) + SUM(correct)
) DESC
LIMIT 500
解释扩展:
id select_type table type possible_keys key key_len ref rows filtered Extra
------ ----------- ----------- ------ ------------------------- -------------- ------- ------ ------ -------- ---------------------------------------------------------------------
1 SIMPLE maths_score ref scoretable,fulltablething fulltablething 51 const 10631 100.00 Using index condition; Using where; Using temporary; Using filesort
当前索引(我尝试过很多)
Keyname Type Unique Packed Column Cardinality Collation Null Comment
uniqueid BTREE Yes No uniqueid 21262 A No
scoretable BTREE No No timestamp 21262 A Yes
lang 21262 A Yes
fulltablething BTREE No No lang 56 A Yes
timestamp 21262 A Yes
user 21262 A Yes
【问题讨论】:
-
重要的是要理解您的“order by”子句要求 mysql 在发出任何内容之前对所有输出进行排序,因为该子句包含计算值。
-
要提高同一队列的性能,您需要创建 3 个索引。 (我认为当前的索引不正确)。 1- TIMESTAMP + lang 上的 Index1 2- USER 上的 index2 和 3- index3 上正确的。注意:索引中列的顺序很重要。
标签: mysql performance indexing group-by