天天看點

記錄一次mysql百萬十萬資料連表查詢優化,300秒優化到0.2秒,速度提升千倍!

今天打開網站的訂單清單頁面,加載超久,最後還502了,資料庫跑滿無法使用導緻第三方平台推送失敗。

訂單有接近17萬條,網站使用者400,改sql加載200~300秒

SELECT `a`.`shop_id`,
        `a`.`ctime`,
        `a`.`status`,
        `a`.`order_id`,
        `a`.`total`,
        `w`.`s_name`,
        `a`.`result`,
        `w`.`shop_type`,
        `a`.`originalPrice`
FROM `shop_orders` `a`
INNER JOIN `shop_config` `w`
    ON `w`.`id`=`a`.`shop_id`
WHERE ( w.store_id=1 )
        AND ( w.delete_time =0 )
ORDER BY  `a`.`ctime` DESC LIMIT 0,30
           

經測試,單表提取資料也是1秒以下,但是連表就出現幾分鐘的響應。

記錄一次mysql百萬十萬資料連表查詢優化,300秒優化到0.2秒,速度提升千倍!

在幾個老哥線上指導,均無法排排除問題,把訂單清單頁面都替換上了“暫時維護”的提示了。因為是阿裡聚石塔RDS,也無法導出這十幾萬資料庫到本地測試。

當然也不排除是資料庫配置太低,畢竟1g1核。計劃臨時更新資料庫配置看,為了保證不影響網站的使用,可以設定為在指定時間替換,在掏錢的時候,還是想再搜搜相關資料。

看到一篇文章,說可以把連表查詢改為子查詢。

SELECT shop_id,
       ctime,
       a.status,
       order_id,
       total,
       (select s_name from shop_config where id= a.shop_id) as s_name,
       (select shop_type from shop_config where id= a.shop_id) as shop_type,
       result,
       originalPrice
  FROM `shop_orders` `a`
 ORDER BY `ctime` DESC
 LIMIT 0,30
           
記錄一次mysql百萬十萬資料連表查詢優化,300秒優化到0.2秒,速度提升千倍!

起初以為結束了,但是又一個老哥提醒到我,這樣我就無法給shop_config 加條件限制了。此時我又想到了,還是用連表查詢,join是可以使用子查詢的。

SELECT `a`.`shop_id`,
       `a`.`ctime`,
       `a`.`status`,
       `a`.`order_id`,
       `a`.`total`,
       `c`.`s_name`,
       `c`.`shop_type`,
       `c`.`store_id`,
       `result`,
       `originalPrice`
  FROM `shop_orders` `a`
  INNER JOIN(SELECT * FROM `shop_config`  WHERE `store_id`= 1) `c` ON `a`.`shop_id`= `c`.`id`
 ORDER BY `a`.`ctime` DESC
 LIMIT 0,30
           
記錄一次mysql百萬十萬資料連表查詢優化,300秒優化到0.2秒,速度提升千倍!

正式結束。

你好,我是勤勤學長。

www.11ak.cn

QQ微信同号318692996