高性能MySQL笔记(一个奇怪的问题)

创建一个表, id是自增主键, 执行select id from table, 结果如何?

mysql5.6

创建表

CREATE TABLE `test_index6` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(45) DEFAULT NULL,
  `name2` varchar(45) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`) using btree
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

插入数据, 执行50次.

insert into test_index6(name,name2,age) values(substring(MD5(RAND()),1,10),substring(MD5(RAND()),1,10),rand()*50);

执行查询数据, select id from test_index6

执行查询数据, select id,name from test_index6

添加索引name

执行语句alter table test_index6 add key name(name);添加索引, 然后查询select id from test_index6

排序变了! 再查询select id,name from test_index6

可以看出, 顺序与只查id时相同. 这说明只查id时, 是按索引name来排序的.
查询select id,name2 from test_index6

排序是按id排的.

添加索引name2

执行语句alter table test_index6 add key name2(name2);添加索引, 再执行查询.



可以看出前2个查询的结果保持不变, 第3个结果按name2的索引进行排序.

分析

上面的查询里可以看出几个点的. 我们可以在查询语句前加上explain进行分析.

  1. "select id"是按第一个索引排序.
  2. "select id+非索引列"按id排序.
  3. "select id+索引列"按索引列排序.
    explain select id from test_index6;, 索引查找

    explain select id,age from test_index6;, 全表扫描

    explain select id,name2 from test_index6;, 索引查找
posted @ 2020-03-07 13:59  Panda110  阅读(130)  评论(0编辑  收藏  举报