昨天接到一個客戶的問題,電腦上能夠打開網站,在手機上確不能打開報500的錯。首先登錄上客戶的服務器查看環境apache+mysql+php,php和mysql的佔用都比較高,按經驗來講那就是mysql的問題了,登錄mysql用show processlist查看進程,發現一條查詢一直在sending datephp
mysql> show processlist; +------+------+-----------------+--------+---------+------+--------------+------ -------------------------------------------------------------------------------- ----------------+ | Id | User | Host | db | Command | Time | State | Info | +------+------+-----------------+--------+---------+------+--------------+------ -------------------------------------------------------------------------------- ----------------+ | 1832 | root | localhost:53490 | NULL | Query | 0 | NULL | show processlist | | 1842 | root | localhost:53508 | yungou | Query | 4 | Sending data | selec t a.id,a.q_user,a.q_showtime,a.thumb,a.title,a.q_uid,qishu,announced_type,q_end_ time ,(SELECT ` | +------+------+-----------------+--------+---------+------+--------------+------ -------------------------------------------------------------------------------- ----------------+ 2 rows in set (0.00 sec)
明顯不對啊,把這條語句單獨拿出來執行也是慢得要死48s。mysql
explain分析一下這條語句:sql
mysql> explain select a.id,a.q_user,a.q_showtime,a.thumb,a.title,a.q_uid,qishu,a nnounced_type,q_end_time ,(SELECT `time` FROM `go_member_go_record` WHERE shopid = a.id ORDER BY `time` DESC LIMIT 1 ) as gm_time from `go_shoplist` as a where `shenyurenshu` <=0 ORDER BY `gm_time` DESC LIMIT 4\G; *************************** 1. row *************************** id: 1 select_type: PRIMARY table: a type: range possible_keys: shenyurenshu key: shenyurenshu key_len: 4 ref: NULL rows: 945 Extra: Using where; Using filesort *************************** 2. row *************************** id: 2 select_type: DEPENDENT SUBQUERY table: go_member_go_record type: index possible_keys: shopid key: time key_len: 63 ref: NULL rows: 1 Extra: Using where 2 rows in set (0.00 sec)
一看type是range就悲劇了,慢是確定的了,可是945條記錄也不至於這麼慢啊!!
apache
沒辦法用簡化法來定位錯誤,先去掉子查詢,直接服務器
select a.id,a.q_user,a.q_showtime,a.thumb,a.title,a.q_uid,qishu,announced_type,q_end_time from `go_shoplist` as a where `shenyurenshu` <=0 ORDER BY `gm_time` DESC LIMIT 4;
沒有問題,速度槓槓的~~ide
那就是子查詢的問題了哦,從哪裏動刀呢?order by desc limit網站
首先去掉排序,查詢槓槓的~~ui
而後想一想order by desc limit 1怎麼替代呢,這句的意思是查詢最大的值,那我直接用max能夠嗎?立刻修改排序
select a.id,a.q_user,a.q_showtime,a.thumb,a.title,a.q_uid,qishu,announced_type,q_end_time ,(SELECT MAX(`time`) FROM `go_member_go_record` WHERE shopid = a.id ) as gm_time from `go_shoplist` as a where `shenyurenshu` <=0 ORDER BY `gm_time` DESC LIMIT 4;
打開網站,哈哈,速度槓槓的~~進程