网站建设知识
高性能MySql进化论(十一):常见查询语句的优化
2025-07-22 11:13  点击:0

高性能MySql进化论(十一):常见查询语句的优化,总结一下常见查询语句的优化方式。

1 COUNT

1. COUNT的作用

· COUNT(table.filed)统计的该字段非空值的记录行数

· COUNT(*)或者是COUNT(not nullable field) 统计的是全表的行数

如果要是统计全表记录数,COUNT(*)效率会比COUNT(not nullable field)要高一点

2. MYISAM的COUNT

一般执行COUNT操作时需要扫描大量的记录,但是在MyISAM引擎的数据库中,数据库把表的记录数保存起来,所以COUN(*)会非常的快(前提是不包含where条件)

3. 当需要频繁的使用COUNT时,可以考虑使用汇总表的策略

4. 优化小例子
在MYISAM中进行范围查询时,可以减少检索行数的小技巧
原始的: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的表达式中只包含一个表的字段

3 优化子查询

尽量用关联代替子查询

4 优化Group by 以及Distinct

1. 当对关联查询执行group by操作时,使用查询表的标识列作为分组条件效率会比较高

2. 当需要查询的非group by指定的字段时,正常情况下是无法执行的,可以通过inner join 的形式来弥补

select firstname, lastnamefrom actorinner join(select actor_id, count(*) as cnt from actor group by(actor_id))using (actor_id)select field1,field2,field3from table1inner join(select id from table1 limit 100, 20) as tempusing(id)