Heim  >  Artikel  >  Datenbank  >  Mysql优化原则_MySQL

Mysql优化原则_MySQL

WBOY
WBOYOriginal
2016-06-08 08:50:41986Durchsuche

二、原则总结

原则1、仅列出需要查询的字段,这对速度不会明显的影响,主要是考虑节省应用程序服务器的内存。

原来语句: select * from admin

优化为: select admin_id,admin_name,admin_password from admin

原则2、尽量避免在列上做运算,这样导致索引失效。

原语句: select * from admin where year(admin_time)>2014

优化为: select * from admin where admin_time> '2014-01-01′

原则3、使用JOIN 时候,应该用小的结果驱动大的结果(left join 左边表结果尽量小 如果有条件应该放到左边先处理,right join 同理反向),同事尽量把牵涉到多表联合的查询拆分多个query(多个连表查询效率低,容易到之后锁表和阻塞)。

原来语句 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 lef join log on T1.admin_id = log.admin_id

原则 4、注意LIKE 模糊查询的使用, 避免使用 %% ,可以使用 后面带% ,双%是不走索引的。

原来语句: select * from admin where admin_name like ‘%de%'

优化为: select * from admin where admin_name >='de' and admin_nam

原则5、使用批量插入节省交互 (当如如果使用存储过程来处理批量的sql 各种逻辑是更好的选择)。

原来语句: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′)

原则6、limit 的基数比较大时使用between。

原来语句:select * from admin order by admin_id limit 100000,10

优化为: select * from admin where admin_id between 100000 admin 100010 order by admin_id

原则7、不要使用rand函数获取多条随机记录。

原来语句: 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

原则8、避免使用NULL。

原则9. 不要使用 count(id) 使用 count(*)。

原则10、不要做无谓的排序操作,而应该使用索引完成排序。

 

三、总结

数据库优化包括两个方面,一方面是SQL程序优化,另一方面是数据库配置的优化。另外在MySQL可以通过以下语句来查看帮助SQL进行优化:

 

复制代码代码如下:
set @@profiling = 1;
select * from typecho_comments order mail limit 10,30;
show profiles;

show profile for query

 

mysql

用那个

关键字分析

sql

语句性能

mysql

用那个

关键字分析

sql

语句性能

mysql

用那个

关键字分析

sql

语句性能

mysql用那个关键字分析sql语句性能?

如上 用 show profiles;

mysql

用那个

关键字分析

sql

语句性能





mysql

用那个

关键字分析

sql

语句性能




mysql

用那个

关键字分析

sql

语句性能



mysql

用那个

关键字分析

sql

语句性能


Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn