先前一直對sql語句優化沒有太在乎,最近**使用者量增加,發現資料庫壓力很大自己寫的語句啊,新來的架構師對我們語句一一優化,我總結如下(不斷更新。。。)
(1)優化前的語句:
# query_time: 5.967435 lock_time: 0.000129 rows_sent: 1 rows_examined: 803401
set timestamp=1286843575;
select livemessag0_.id as id38_, livemessag0_.isactive as isactive38_, livemessag0_.content as content38_, livemessag0_.createtime as createtime38_, livemessag0_.userid as userid38_, livemessag0_.objectid as objectid38_, livemessag0_.recordid as recordid38_, livemessag0_.type as type38_ from live_message livemessag0_ where (livemessag0_.objectid in (select livescrip1_.id from live_scrip livescrip1_ where livescrip1_.senderid='ff8080812aebac2d012aef6491b3666d')) and livemessag0_.type=2 limit 6;
優化後的語句:
select livemessag0_.id as id38_,
livemessag0_.isactive as isactive38_,
livemessag0_.content as content38_,
livemessag0_.createtime as createtime38_,
livemessag0_.userid as userid38_,
livemessag0_.objectid as objectid38_,
livemessag0_.recordid as recordid38_,
livemessag0_.type as type38_
from live_scrip livescrip1_ left join
live_message livemessag0_
on livescrip1_.id=livemessag0_.objectid
where livescrip1_.senderid = 'ff8080812aebac2d012aef6491b3666d' and
livemessag0_.type = 2
limit 6;
[b]總結:盡量少用子查詢用表連線的方式代替(如果表連線不是太複雜的話),這樣優化後大概能減少1/3的時間,後來發現livemessag0_.objectid竟然沒有建立索引,暈菜[/b]
(2)優化前的慢查詢:
select r1.id,r1.username,r1.nickname,r1.img_name,r1.datecreated from acegi_users as r1 join (select round(rand() *(select max(num_id) from acegi_users)) as id) as r2 where r1.num_id >= r2.id and r1.id not in(select r.user_id from user_relations r where r.relation_user_id='ff8080812ad5ad7f012ad5aee5150005') and r1.id!='ff8080812ad5ad7f012ad5aee5150005' and r1.role='expert' order by r1.num_id limit 3;
優化後的sql:
select r1.id,
r1.username,
r1.nickname,
r1.img_name,
r1.datecreated
from acegi_users as r1
join
(select round(rand() *(select max(num_id) from acegi_users)) as id) as r2
where r1.num_id >= r2.id
andnot exists (select r0.user_id from (select r.user_id from user_relations r where
r.relation_user_id = 'ff8080812ad5ad7f012ad5aee5150005' union select 'ff8080812ad5ad7f012ad5aee5150005') r0 where r0.user_id=r1.id)
andr1.role = 'expert'
order by r1.num_id
limit 3;
[b]總結:少用not in 用not exists代替之[/b]
sql 語句優化總結
我們如何更迅速的從乙個大型專案中,知道是什麼影響了服務的效能。mysql 提供了一些常用的命令來查詢資料庫的執行狀態。1.show status like uptime 檢視mysql資料庫執行了多長時間 2.show status like com select 檢視mysql 資料庫的查詢次數 ...
SQL語句優化總結
開發過程中必不可少的就是對資料庫的操作,也就離不開sql語句的書寫,我們也就需要考慮到sql語句的執行速度,需要書寫規範和優化。1.避免進行全表掃瞄。避免使用 select 用表中具體的列來查詢 select from user select id,name,phone,from user 2.避免...
SQL 語句優化總結
個人日常優化sql語句的總結筆記 目前 db 承受 日平均 500w pv 左右的站點,資料檔案大小在20g左右,表資料量 在 50 500 w 左右 僅供參考 1 查詢的資料行分布情況,決定索引是否用得上,如果查詢的資料行在資料表中分布均勻,且所佔比重較大,能用上索引 反之,用不上索引 2 sel...