创建一个表格一个是主键列一个是索引列然后插入一批数据调用select * from test_b可以发现输出结果并没有按照Id有序而是按照Type有序
如果希望按照Id有序可以使用force index (primary)这一hint语句
mysql> CREATE TABLE `test_b` (
> `Id` int() NOT NULL
> `Type` int() DEFAULT NULL
> PRIMARY KEY (`Id`)
> KEY `IDX_Type` (`Type`)
> ) ENGINE=InnoDB DEFAULT CHARSET=utf;
Query OK rows affected ( sec)
mysql> insert into test_b values()()()()();
Query OK rows affected ( sec)
Records: Duplicates: Warnings:
mysql> select * from test_b;
+++
| Id | Type |
+++
| | |
| | |
| | |
| | |
| | |
+++
rows in set ( sec)
mysql> select * from test_b force index (primary);
+++
| Id | Type |
+++
| | |
| | |
| | |
| | |
| | |
+++
rows in set ( sec)
观察select * from test_b的前两条结果()()当Type相等的时候按照Id排序为了确认这一点再多插入点数据观察结论相同
mysql> insert into test_b values()()();
Query OK rows affected ( sec)
Records: Duplicates: Warnings:
mysql> select * from test_b ;
+++
| Id | Type |
+++
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
+++
rows in set ( sec)
默认情况下为什么会结果按照索引列有序呢?这还要从数据库内部的运行机制说起首先系统会查询索引表(test_b_indexed_type)该索引表的主键是索引列type(通常为了保证主键唯一性type后面会添加一个id后缀)通过索引列查到Id然后拿着这些Id去test_b中查询最终结果为了最高效扫描索引表的时候会顺着type主键往下扫然后拿扫得的id去“逐个”请求test_b于是自然就出现了按照索引列有序的结果
当Type列的值一致的时候插入到索引列的数据可以根据Id顺序插入到索引表中保证了当Type一致的时候会按照Id排序