有关THE索引的select *和select列的区别

时间:2017-03-14 15:57:00

标签: mysql

索引使用的示例如下所示:create table query:

drop table test_index;
create table test_index(
    id bigint not null auto_increment ,
    `name` varchar(20) not null default '',
    uid bigint not null default 0,
    a int not null default 0,
    b int not null default 0,
    primary key(id),
    index `a_b`  (a,b) 
);

之间的区别是什么
select  * from test_index where a =10

select name from test_index where a=10 

关于THE index。

-------更新---------

也许问题是

之间的区别是什么
select  * from test_index where a =10

select a from test_index where a=10 

关于THE index。

1 个答案:

答案 0 :(得分:1)

MySQL索引有几个目标。可能最常见的是:

  • 查找匹配WHERE子句的行。
  • 放弃考虑的行。

有关详细信息,请check here

但是在两个查询中查看运行解释的结果,似乎显示出一些差异。

explain select * from test_index where a = 10;
+----+-------------+------------+------------+------+---------------+------+---------+-------+------+----------+-------+
| id | select_type | table      | partitions | type | possible_keys | key  | key_len | ref   | rows | filtered | Extra |
+----+-------------+------------+------------+------+---------------+------+---------+-------+------+----------+-------+
|  1 | SIMPLE      | test_index | NULL       | ref  | a_b           | a_b  | 4       | const |    1 |   100.00 | NULL  |
+----+-------------+------------+------------+------+---------------+------+---------+-------+------+----------+-------+

explain select a from test_index where a = 10;
+----+-------------+------------+------------+------+---------------+------+---------+-------+------+----------+-------+
| id | select_type | table      | partitions | type | possible_keys | key  | key_len | ref   | rows | filtered | Extra |
+----+-------------+------------+------------+------+---------------+------+---------+-------+------+----------+-------+
|  1 | SIMPLE      | test_index | NULL       | ref  | a_b           | a_b  | 4       | const |    1 |   100.00 | NULL  |
+----+-------------+------------+------------+------+---------------+------+---------+-------+------+----------+-------+

如果我们专注于Extra字段,我们会发现存在差异。对于第一个查询,其值为 null ,而使用索引表示第二个查询。

查看文档,我们可以看出这些差异意味着什么:

  • 来自Extra列中使用索引值的explain docs仅使用索引树中的信息从表中检索列信息,而无需执行额外的搜索来读取实际行。当查询仅使用属于单个索引的列时,可以使用此策略。

  • 对于另一种情况,根据index type docs Null 值将使用来自此索引的读取执行完整扫描表,以查找相应索引顺序中的数据行。