我创建了一个包含 100k 行的测试表。此查询的执行时间:
SELECT id FROM table
是0.032s。如果我GROUP BY为索引为 的整数列添加语句,Normal,BTREE则查询的执行时间:
SELECT id FROM table GROUP BY indexedColumn
解释输出:
id | select_type | table | type | possible keys | key | key_len | ref | rows | Extra
1 SIMPLE [table] All [indexedColumnKey] null null null 105416 Using temporary; Using filesort
是0.073s。由于 ,执行时间加倍GROUP BY,但我假设这是正常的?我的问题是为什么要添加LIMIT到查询中,如下所示:
SELECT id FROM table GROUP BY indexedColumn LIMIT 500
解释输出:
id | select_type | table | type | possible keys | key | key_len | ref | rows | Extra
1 SIMPLE [table] index [indexedColumnKey] [indexedColumnKey] 5 null 500 null
将执行时间增加到0.301s? 这是超过 4 倍的减速。
我对 SQL 非常缺乏经验,所以这可能是完全正常的,但对我来说,限制返回的行数会大大降低查询速度,这似乎违反直觉。
问题:
- 这是正常的吗?
- 有什么办法可以阻止 LIMIT 减慢查询速度?