SQL索引优化
在 where 从句,group by 从句,order by 从句,on 从句中出现的列
索引字段越小越好
离散度大的列放到联合索引的前面
SELECT FROM payment WHERE staff_id 2 AND customer_id 584;
是 index(sftaff_id, customer_id)好?还是 index(customer_id, staff_id)好?
由于 customer_id 的离散度更大,所以应该使用 index (customer_id, staff_Id)
离散度大的列放到联合索引的前面
1.索引的建立:
在条件从句中建立索引:
如:where , order by, group by, on 从句
2. 索引字段越小越好。
使得一页存储的数据量增大,使得io效率更好。
3.离散度大的列放到联合索引前面,离散度高,可选择性更好,放在前面效果越好;
判断列离散度的语句
select count(distinct custom_id), count(distinct staff_id) from payment;
所以选择联合索引 index(custom_id,staff_id)
mysql数据库索引优化
索引添加的优化
sql及索引优化
索引优化 :选择合适列
离散度大的列放在联合索引的前面
建立联合索引:离散度大的放在前面;
离散度查询: select count(distinct custom_id),count(distinct staff_id) from table;
count的数值越大说明离散度越大,则建立联合索引就放前面;index(customer_id,staff_id);
如何判断一个表的离散度?
查看表的数据结构信息 desc 表名;
判断某一列的离散度:select count(distinct 字段名)from 表名;返回的结果值越大,说明离散度越大,建立联合索引时,应该放到前面;
选择合适的索引列
1.在where,group by,order by,on从句中出现的列
2.索引字段越小越好(因为数据库的存储单位是页,一页中能存下的数据越多越好 )
3.离散度大的列放在联合索引前面
select count(distinct customer_id), count(distinct staff_id) from payment;
是index(sftaff_id,customer_id)好?还是index(customer_id,staff_id)好呢?
由于customer_id的离散度更大,所以应该使用index(customer_id,staff_id)好。
离散度:数据唯一值越多,离散度越高。例如, select count(distinct id),count(distinct real_name) from user; id 是唯一值,所以离散度更高。而 real_name 会出现重复—>会有同名同姓的情况,所以离散度低。
查看离散度 通过统计不同的列值来实现 count越大 离散程度越高
如何选择合适的列建立索引
如何选择合适的列建立索引?
在where从句,group by 从句,order by从句,on从句中出现的列
索引字段越小越好
离散度大的列放到联合索引的前面
如何选择合适的列建立索引
如何选择合适的列建立索引