一、建表
1、不要使用使用NULL字段,设置字段默认值
bad case:
name
char(32) default null
age
int not null
good case:
name
char(32) not null default ”
age
int not null default 0
2、用好数值类型
tinyint(1Byte)
smallint(2Byte)
mediumint(3Byte)
int(4Byte)
bigint(8Byte)
bad case:
int(1)/int(11)
3、优先使用enum或set
例如:sex
enum (‘F’, ‘M’)
4、少用text/blob
varchar的性能会比text高很多;
实在避免不了blob,请拆表;
5、控制列数量
字段少而精,字段数建议在20以内;
6、拒绝3B
拒绝大sql语句:big sql
拒绝大事物:big transaction
拒绝大批量:big batch
二、查询
1、不用select *
消耗cpu,io,内存,带宽;
这种程序不具有扩展性;
2、sql语句尽可能简单
一条sql只能在一个cpu运算;
大语句拆小语句,减少锁时间;
一条大sql可以堵死整个库;
3、简单的事务
事务时间尽可能短;
bad case:
上传图片事务
4、limit高效分页
limit越大,效率越低
select id from t limit 10000, 10;(返回10001-10010行)
=>
select id from t where id > 10000 limit 10;
5、使用group by
分组;
自动排序;
6、不在索引做列运算