如何提高这个SQL查询性能?

时间:2015-05-27 07:47:17

标签: mysql

SELECT id, name, detail FROM student WHERE id NOT IN (1,788,103,100) ORDER BY id DESC LIMIT 1000,10

表很小(10,000行)。我必须考虑两点,“IN查询”和“LIMIT查询”。

以下是DDL和EXPLAIN。我正在使用MySQL 5.6.4。

CREATE TABLE student 
( id int(11) NOT NULL AUTO_INCREMENT 
, name varchar(45) NOT NULL
, detail varchar(255) NOT NULL 
, PRIMARY KEY (id)
) ENGINE = MyISAM;

| id | select_type | table  | type | possible_keys | key  | key_len | ref  | rows | Extra | 
|  1 | SIMPLE      | student| ALL  | Primary,id    | NULL | NULL    | NULL | 13   |       | 

2 个答案:

答案 0 :(得分:1)

LIMIT和ORDER BY子句意味着查询必须构建整个表,然后对其进行排序,然后转到记录1000,然后提取接下来的10个记录。

为什么要查找从记录1000开始的10条记录?

删除ORDER BY子句会使其更快,因为查询只需要提取1010条记录。

答案 1 :(得分:0)

我不能复制这个发现......

SELECT VERSION();
+-----------+
| VERSION() |
+-----------+
| 5.5.16    |
+-----------+

SELECT COUNT(*) FROM student;
  +----------+
  | COUNT(*) |
  +----------+
  |   131072 |
  +----------+

SELECT id
  FROM student
 WHERE id
   NOT IN (1,788,103,100)
 ORDER
    BY id DESC
 LIMIT 1000,10;
  +--------+
  | id     |
  +--------+
  | 195591 |
  | 195590 |
  | 195589 |
  | 195588 |
  | 195587 |
  | 195586 |
  | 195585 |
  | 195584 |
  | 195583 |
  | 195582 |
  +--------+
  10 rows in set (0.00 sec)

+----+-------------+---------+-------+---------------+---------+---------+------+--------+--------------------------+
| id | select_type | table   | type  | possible_keys | key     | key_len | ref  | rows   | Extra                    |
+----+-------------+---------+-------+---------------+---------+---------+------+--------+--------------------------+
|  1 | SIMPLE      | student | range | PRIMARY       | PRIMARY | 4       | NULL | 131069 | Using where; Using index |
+----+-------------+---------+-------+---------------+---------+---------+------+--------+--------------------------+