mysql分組查詢效能優化 MySQL分組查詢優化

2021-10-18 03:26:51 字數 1464 閱讀 5788

我有三個表:類別,文章和article_events,具有以下結構

categories: id, name (100,000 rows)

articles: id, category_id (6000 rows)

article_events: id, article_id, status_id (20,000 rows)

每篇文章行的最高article_events.id描述了每篇文章的當前狀態.

我正在返回乙個類別表,其中包含最近事件status_id為「1」的文章數量.

到目前為止我的工作,但是我的桌子大小相當慢(10秒).想知道是否有辦法讓這更快.據我所知,所有表都有適當的索引.

select c.id,

c.name,

sum(case when e.status_id = 1 then 1 else 0 end) article_count

from categories c

left join articles a on a.category_id = c.id

left join (

select article_id, max(id) event_id

from article_events

group by article_id

) most_recent on most_recent.article_id = a.id

left join article_events e on most_recent.event_id = e.id

group by c.id

基本上我必須兩次加入事件表,因為要求status_id和max(id)只返回它找到的第乙個status_id,而不是與max(id)行相關的那個.

有什麼辦法讓這更好嗎?或者我只需要活10秒鐘?謝謝!

這是我的explain查詢:

id | select_type | table | type | possible_keys | key | key_len | ref | rows | extra

1 | primary | c | index | null | primary | 4 | null | 124044 | using index; using temporary; using filesort

1 | primary | a | ref | category_id | category_id | 4 | c.id | 3 |

1 | primary | | all | null | null | null | null | 6351 |

1 | primary | e | eq_ref | primary | primary | 4 | most_recent.event_id | 1 |

2 | derived | article_events | all | null | null | null | null | 19743 | using temporary; using filesort

mysql查詢效能優化 MySQL 查詢效能優化

在日常開發中,程式設計師寫的最多的除了bug之外,應該算是sql語句了。sql的質量影響了程式的響應速度,只有利用mysql的特性,才能讓mysql更有效的執行查詢sql,充分發揮mysql的優勢,並避開它的弱點。為什麼查詢速度會慢?在編寫sql之前,需要清楚一點 真正重要的是響應時間。如果我們把查...

mysql 查詢效能優化

mysql 執行查詢,客戶端向 mysql 傳送請求的時候,mysql 伺服器執行一系列過程,保證查詢語句在 mysql 中得到最高效能的效率。客戶端傳送一條查詢給伺服器 2 伺服器先檢查查詢快取,如果命中了快取,則返回儲存在快取中的結果。否則,進入下乙個階段。3 伺服器進行 sql解析 預處理,再...

mysql查詢效能優化

mysql執行查詢的過程 如圖 1 客戶端首先通過客戶端 伺服器通訊協議與mysql伺服器建立起連線 2 客戶端傳送一條sql語句 判斷是否為查詢語句,如果是查詢語句,則先在查詢快取區雜湊查詢對應sql的資料,如果未找到,則需要呼叫解析器解析 預處理 再由優化器生成對應的查詢執行計畫 3 mysql...