mysql索引優化
索引化方向;
數據表結構
- 字段數儘量在20個以內;
- 儘量標出字段的長度;
- 字段儘量用數字表示: 省磁盤,省IO;比較也比字符串高效
- text類型儘量分表存儲;
- 儘量不設可爲null的字段;
單表數據量超500W 條 或 2G,即可考慮分表;
sql及索引
測試表結構及索引
-- create table idx (
-- id int PRIMARY key auto_increment ,
-- a1 int,
-- a2 int,
-- a3 int,
-- a4 int,
-- a5 int);
-- create index idx_a1234 on idx(a1,a2,a3,a4);
-- insert into idx(a1,a2,a3,a4,a5) value(1,2,3,4,5);
-- insert into idx(a1,a2,a3,a4,a5) select a1+1,a2+1,a3+1,a4+1,a5+1 from idx where id = (select max(id) from idx);
索引
system -> const -> eq_ref -> ref -> range -> index -> all;
單條數據表 主鍵 相聯表惟一索引 關聯表索引
order by
當 order by 中存在 desc 或者 字段順序 不匹配 索引字段順序時,不會用到索引。
當 order by 中存在 都是 asc或者 字段順序 匹配 索引字段順序時,會用到索引。
- explain select * from idx where a1 =1 order by a2 desc, a3 desc;
- explain select * from idx where a1 =1 GROUP BY a2,a3;
group by
當 group by 中存在字段順序 不匹配 索引字段順序時,不會用到索引。
當 group by 中存在 字段順序 匹配 索引字段順序時,會用到索引。
- explain select * from idx where a1 =1 GROUP BY a3,a2;