这里的原则 只是针对mysql数据库,其他的数据库 某些是殊途同归,某些还是存在差异。我总结的也是mysql普遍的规则,对于某些特殊情况得特殊对待。在构造sql语句的时候养成良好的习惯
原来语句: select * from admin
优化为: select admin_id,admin_name,admin_password from admin
原语句: select * from admin where year(admin_time)>2014
优化为: select * from admin where admin_time> '2014-01-01'
原来语句 select * from admin left join log on admin.admin_id = log.admin_id where log.admin_id>10
优化为: select * from (select * from admin where admin_id>10) T1 left join log on T1.admin_id = log.admin_id
原来语句: select * from admin where admin_name like '%de%'
优化为: select * from admin where admin_name >='de' and admin_nam <'df' (注意不是等效的这里试试提供优化的思路)
原来语句:insert into admin(admin_name,admin_password) values ('test1','pass1');
insert into admin(admin_name,admin_password) values ('test2','pass2');
insert into admin(admin_name,admin_password) values ('test3','pass3')
优化为: insert into admin(admin_name,admin_password) values('test1','pass1'),('test2','pass2'),('test3','pass3')
原来语句:select * from admin order by admin_id limit 100000,10
优化为: select * from admin where admin_id between 100000 admin 100010 order by admin_id
原来语句: select * from admin order by rand() limit 20
优化为: select * from admin as t1 Join(select round(rand()*((select max(admin_id) from admin)-(select min(id) from admin))+(select min(id) from admin)) as id) as t2 where t1.id>=t2.id order by t1.id limit
数据库优化包括两个方面,一方面是sql 程序优化,另一方面是数据库配置的优化。另外在mysl 可以通过 以下语句来查看帮助sql进行优化
set @@profiling = 1; select * from typecho_comments order mail limit 10,30; show profiles; show profile for query *