原始的:select count(*) from dictionary where id>5.
优化后:select (select count(*) fromdictionary)-count(*) from dictionary where id<=5
减少查询次数
优化前:需要两条语句
Select count(*)from student where area=’SH’
Select count(*)from student where area=’BJ’
优化后:合并成一条
select count(area='SH') as shcount, count(area='BJ') as bjcount from student;
2优化关联查询
1. 确保ON或USING的字句上有索引
2. 一般情况下只需要在第二个表上创建索引
3. 尽量使 Group by/Order by的表达式中只包含一个表的字段
select firstname, lastname
from actor
inner join(select actor_id, count(*) as cnt from actor group by(actor_id))
using (actor_id)
3. group by默认会对查询的结果进行排序,数据量很大的时候可能会比较耗资源,如果你不关心查询结果的顺序,可以通过order by null 避免这种不必要的浪费
7自定义变量
合理灵活的使用自定义变量往往会给程序的性能带来意想不到的效果,但往往也会带来与其他数据库系统的兼容性问题。
下面列出几个自定义变量使用的小例子
·行号
mysql> set @rownumber:=0;
mysql> select mean, @rownumber:=@rownumber+1 from dictionary limit10;
·避免重复查询刚刚更新的数据
在更新完一条记录后,往往需要再次执行select查询刚刚更新过的记录
通过变量可以避免这种问题
Mysql>set @updaterow:=null;
mysql> update dictionary set mean='update get variable' where id=100and @updaterow:=now();
·统计更新和插入的数量
mysql> set @x:=0; //define avariable
mysql> insert into dictionary (id,mean) values(3,'duplicate') onduplicate key update mean=values(mean)+(0*(@x:=@x+1)); //insert a duplicaterecord
mysql> select @x; //get x value, it’s indicator duplicate times