記兩則親身經歷的sql優化技巧:
一、主表數據不到100萬,以下查詢結果集約200左右,第一條sql執行效率為40ms,第二條為200ms,使用上面方法,其效率明顯優於left join:
sql1:
SELECT SQL_NO_CACHE usersr_id ,businessunit_id ,ifnull((SELECT name FROM sync_businessunit WHERE id= obj.businessunit_id),'無名' ) businessunit_name ,ifnull((SELECT fullname FROM sync_usersys WHERE id= obj.usersr_id),'無名' ) sr_name ,SUM(price) price ,IFNULL((SELECT target FROM analysis_target WHERE year=2017 and month=4 and usersr_id = obj.usersr_id ),0) target FROM analysis_cusorder obj WHERE send_time >= '2017-02-01' AND send_time < '2017-03-01' #BETWEEN '2017-02-01' and '2017-02-28' GROUP BY usersr_id ORDER BY usersr_id;
sql2:
SELECT SQL_NO_CACHE o.usersr_id, o.businessunit_id, u.`name` as businessunit_name, us.fullname, t.target as zongzhibiao, SUM(o.price) as zongdacheng FROM analysis_cusorder o LEFT JOIN analysis_target t ON o.usersr_id = t.usersr_id and t.`year`=2017 and t.`month` = 4 LEFT JOIN sync_businessunit u ON o.businessunit_id = u.id LEFT JOIN sync_usersys us ON o.usersr_id = us.id WHERE o.send_time BETWEEN '2017-02-01' and '2017-02-28' GROUP BY o.usersr_id;
二、為針對limit的優化,一般表數據超過1000萬,limit基本就廢了,需采用sql1的方法進行優化,效率相關極為明顯,以下語句為使用php框架后的寫法:
sql1:
$query = $this->db->select('id,third_id,recommend_menus')->where("id > $maxid and recommend_menus != ''")->order_by("id asc")->limit($perpage)->get('crawler_merchant');
sql2:
$query = $this->db->select('id,third_id,recommend_menus')->limit($perpage, $offset)->get('crawler_merchant');