create table yw (

id int unsigned not null auto_increment,

c1 int not null default '0',

c2 int not null default '0',

primary key(id)

); 


创建一个存储过程call insert_yw往表中插入数据


插入时设置两个参数,提高插入性能

innodb_flush_log_at_trx_commit = 0

sync_binlog = 0


call insert_yw(4500000);


select count(*) from yw;

+----------+

| count(*) |

+----------+

|  4500000 |

+----------+

1 row in set (2.06 sec)


是2.06秒


加上辅助索引后


create index id_c1 on yw(c1);


>select count(*) from yw;

+----------+

| count(*) |

+----------+

|  4500000 |

+----------+

1 row in set (0.68 sec) 


为什么用 secondary index 扫描反而比 primary key 扫描来的要快呢?我们就需要了解innodb的clustered index 和 secondary index 之间的区别了。 


innodb 的 clustered index 是把 primary key 以及 row data 保存在一起的,而 secondary index 则是单独存放,然后有个指针指向 primary key。因此,需要进行 count(*) 统计表记录总数时,利用 secondary index 扫描起来,显然更快。