• 高性能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;, 索引查找
  • 相关阅读:
    164.Maximum Gap
    163.Missing Ranges
    162.Find Peak Element
    161.One Edit Distance
    160.Intersection of Two Linked Lists
    7.5爬取猫眼Top100电影名单
    7.5文件操作
    7.4文件操作(1)
    7.4一个失败的网易云爬虫,
    7.3数据结构(1)
  • 原文地址:https://www.cnblogs.com/winwink/p/HighPerformanceMySql_Question1_Select_ID.html
Copyright © 2020-2023  润新知