批量插入(500-1000)
insert into tb_user values(),(),()
start transaction;
insert into ...
insert into ...
.....
commit;
主键顺序插入:
乱序插入: 8 1 9 21 88 2 4 15 89 5 7 3
顺序插入:1 2 3 4 5 7 8 9 15 21 88 89
insert语句性能较低,此时用MySQL数据库提供的load指令进行插入,操作如下:
#客户端连接服务端时,加上参数 --local-infile
mysql --local-infile -u root -p
#设置全局参数local_infile=1
set global local_infile=1;
#执行load指令将准备好的数据,加载到表结构中
load data local infile '/root/sql/.log'into table 'tb_user' fields terminated by '.' lines terminated by'\n';
主键顺序插入的性能高于乱序插入
在InnoDB存储中,表数据都是根据主键顺序组织存放的,这种存储方式的表称为索引组织表。
页可以为空,也可以填充一半,也可以填充百分之百,每页包含了2-n行数据(如果一行数据过大,会行溢出),根据主键排列
当删除一行记录时,实际上记录上并没有被删除,只是记录被标记为删除,并且它的空间变得允许被其他记录声明使用。当页中删除的记录达到merge_threshold(默认为页的50%)。InnoDB会开始寻找最靠近的页(前或后)看看是否可以将两个页合并以优化空间使用。
merge_threshold:合并页的阈值,可以自己设置,在创建表或者创建索引时指定。
#没有创索引时,根据age,phone进行排序
explain select id,age,phone from tb_user order by age,phone;
#创索引
create index idx_user_age_phone_aa on tb_user(age,phone);
#创索引后,据age,phone进行排序
explain select id, age,phone,from tb_user order by age,phone;
# 降序
explain select id, age,phone,from tb_user order by age desc,phone desc;
#根据age,phone一个升序一个降序。
explain select id, age,phone,from tb_user order by age asc,phone desc;
#创建索引
create idex idx_user_age_phone_aa on tb_user(age asc,phone desc);
#根据age,phone进行降序,一个升序,一个降序。
explain select id,age,phone from tb_user order by age ase,phone desc;
#删掉目前的联合索引
drop index idx_user_pro_age_sta on tb_user;
#执行分组操作,根据profession 字段分组
explain select profession,count(*) from tb_user group by profession;
#创建索引
(profession,age,status)
#执行分组操作
by profession,age
在limit 2000 000 ,10 ,此时需要MySQL排序前2000010记录,仅仅返回2000 000 -2000010 的记录,其他记录丢弃,查询的代价非常大。
优化思路:一般分页查询时,通过创建覆盖索引能够比较好的提高性能,可以通过覆盖索引加子查询形式进行优化。
explain select * from tb_sku,t1(select Td from sb_sku order by id limit 2000000,10) a where t.id=a.id;
explain select count(*) from tb_user;
优化思路:自己计数。
count的几种用法:count()是聚合函数,对返回结界一行一行判断,如果count函数的参数不是null,累计值就加1,否则不加,返回累计值。
用法:count(*)、count(主键)、count(字段)、count(1)
按效率排序:count(字段)< count(主键)< count(1)约等于 count(*),所以尽量使count(*)
InnoDB的行锁是针对索引加的锁,不是针对记录加的锁,并且该索引不能失效,否则会从行锁变成表锁。
尽量根据主键/索引字段进行数据更新。