SELECT COUNT(*)根本不使用任何索引

时间:2018-07-07 03:27:28

标签: mysql laravel

我正在使用Laravel,它是查询生成器的魔术方法paginate。我发现在幕后它在下面使用了类似的查询,处理时间约为3.799秒。

SELECT COUNT(*) as `aggregate` FROM job_descriptions;

当我使用EXPLAIN语句时,结果如下:

+---+-------------+-------+-----------+-------+---------------+
|id |select_type  |table  |partitions |type   |possible_keys  |
+---+-------------+-------+-----------+-------+---------------+
|1  |SIMPLE       |(null) |(null)     |(null) |(null)         |
+---+-------------+-------+-----------+-------+---------------+

+-------+--------+-------+-------+----------+----------------------------+
|key    |key_len |ref    |rows   |filtered  |Extra                       |
+-------+--------+-------+-------+----------+----------------------------+
|(null) |(null)  |(null) |(null) |(null)    |Select tables optimized away|
+-------+--------+-------+-------+----------+----------------------------+

我被告知,我只需要为主键创建另一个索引(例如job_descriptions_id_index),然后在执行计数时使用该索引即可。所以我的查询现在将是这样。

SELECT COUNT(*) AS `aggregate` FROM job_descriptions 
FORCE INDEX(job_descriptions_id_index);

EXPLAIN现在会给我这个:

+---+-------------+-----------------+-----------+-------+---------------+
|id |select_type  |table            |partitions |type   |possible_keys  |
+---+-------------+-----------------+-----------+-------+---------------+
|1  |SIMPLE       |job_descriptions |(null)     |index  |(null)         |
+---+-------------+-----------------+-----------+-------+---------------+

+--------------------------+--------+-------+-------+----------+---------------+
|key                       |key_len |ref    |rows   |filtered  |Extra          |
+--------------------------+--------+-------+-------+----------+---------------+
|job_descriptions_id_index |4       |(null) |54913  |100.00    |Using index    |
+--------------------------+--------+-------+-------+----------+---------------+

所以我想知道我的设置是否有问题,因为第一个EXPLAIN语句的结果显示不多,即使 table 字段为。但是有了FORCE INDEX,我的查询现在快了很多,大约0.819秒。

如果我要使用优化的查询,我的代码将有很多更改,因此我正在寻找一种方法来强制第一个查询使用job_descriptions_id_index而不是全表扫描。 / p>

顺便说一句,我的laravel版本是5.6.26,mysql是8.0.11,我使用InnoDB

0 个答案:

没有答案