两张表左连接索引优化
<code> mysql>explainselect
*from
news a leftjoin
new_type bon
a.type_id=b.TypeId;/<code>
结果:我们看到两张表都是全表扫描,type类型全是ALL,此时性能最差
<code> mysql>create index type_id
on
news
(type_id
); mysql>explainselect
*from
news a leftjoin
new_type bon
a.type_id=b.TypeId;/<code>
结果:左连接给左表加完索引,没有任何效果,并且还是全表扫描,效率极差。
<code> mysql>create index type_id
on
news
(type_id
); mysql>explainselect
*from
news a leftjoin
new_type bon
a.type_id=b.TypeId;/<code>
结果:左连接给右表加完索引,使用到了索引,且还是ref级别的。
两张表右连接索引优化
<code> mysql>explainselect
*from
news a rightjoin
new_type bon
a.type_id=b.TypeId;/<code>
结果:右连接给右表加完索引,没有任何效果,并且还是全表扫描,效率极差。
<code> mysql>explainselect
*from
news a leftjoin
new_type bon
a.type_id=b.TypeId;/<code>
结果:右连接给左表加完索引,使用到了索引,且还是ref级别的。
注意(单表查询)多条件查询:
- 我们创建的联合索引的顺序是category_id、comments、views
结果:虽然使用到了index索引(全表扫描,只是扫描表的时候按照索引次序 进行而不是行。主要优点就是避免了排序, 但是开销仍然非常大),但是产生了文件排序,性能很差
- 创建category_id、views联合索引
结论:如果在where条件中如果有三个查询查询条件key1、key2、key3,其中key2条件是范围查询,
则需要创建key1、key3的复合索引。
结论:
- 左连接索引加右表。
- 右连接索引加左表