sql優化之慢sql優化實踐 點滴

2021-08-20 20:21:28 字數 1266 閱讀 3201

sp_order_day_current     表存在480w條資料

關聯sp_service_site表id的外來鍵sj_site

sp_service_site               

表存在3w條資料

1

2

3

4

5

6

7

8

9

-- in的寫法     22秒

select * from sp_order_day_current where sj_site in(select id from (select id from sp_service_site where site_type=1 limit 0,10)b)

-- exists的寫法    14秒

select a.sj_site from sp_order_day_current a where

exists (select id from (select id from sp_service_site where site_type=1 limit 0,10) b where  a.sj_site= b.id) group by a.sj_site

-- 優化後的結果    1秒不到

select sj_site from sp_order_day_current a join (select id from sp_service_site where site_type=1 limit 0,10) b on (a.sj_site = b.id group by a.sj_site)

總結:先limit,在條件,在分組,在排序。

能用關聯查詢,不用exists判斷,更不用in子查詢。

在日常開發工作中,我們可以做一些工作達到預防慢 sql 問題,比如在上線前預先用診斷工具對 sql 進行分析。常用的工具有:

mysqldumpslow

mysql profile

mysql explain

具體使用及分析方法在此就不贅述,網上有豐富的資源可以參考sp_service_site 表存在3w條資料。

推薦查閱:

使用sql語句監控資料庫效能

資料庫索引優化,和鎖優化

mysql資料庫開發常見問題及優化

mysql面試題

mysql優化之 慢SQL分析

對慢sql優化一般可以按下面幾步的思路 1 開啟慢查詢日誌,設定超過幾秒為慢sql,抓取慢sql 2 通過explain對慢sql分析 重點 3 show profile查詢sql在mysql伺服器裡的執行細節和生命週期情況 重點 4 對資料庫伺服器的引數調優 1 設定慢查詢 1 設定開啟 set ...

優化之慢查詢

查詢超過指定的時間的語句叫慢查詢 檢視慢查詢的指定的時間 show variables like long show status like connections 查詢當前mysql資料庫是否開啟慢查詢日誌功能 show varlables like slow 1.配置慢查詢日誌存放路徑 在磁碟隨...

查詢優化 SQL優化

查詢優化注意點 代表查詢速度比較 1 所有查詢必須注意 的使用必要性 cout 1 cout 2 字段 主鍵索引 字段 普通索引 字段 沒有索引 3 乙個字段 多個字段 欄位多越慢 4 大於10000和大於10001的區別 後者大於前者 5 列沒別名 列 有別名6 兩個條件,where時應該將符合資...