尤川豪   ·  4年前
445 貼文  ·  275 留言

laravel whereHas 很慢( mysql where exist + sub query 效能問題 )

幫客戶查主機效能問題

發現一處程式碼用到 laravel whereHas + sub query,背後會轉為 mysql where exist 指令.

query time 約莫 20 秒

牽扯到的兩張 table 分別有 200 多筆資料 與 20 多萬筆資料

mysql slow query log 顯示, rows_examined 約莫 5000萬筆!這實在很驚人.

隨便換成其他的 eager loading 寫法,query time 便會降到 0.5 秒左右

研究之後發現...


https://github.com/laravel/framework/issues/18415

Laravel is creating a temporary column on literally every row in the database, in which it fills with true or false. If any indexes can be used, they are probably used after this. Any query that uses whereHas is probably going to be a full table scan.


目前小結論:

除非以上問題被解決,否則不要使用 Laravel 的 whereHas 語法!

  分享   共 2,031 次點閱
按了喜歡:
共有 0 則留言
還沒有人留言。歡迎分享您的觀點、或是疑問。
您的留言
尤川豪
445 貼文  ·  275 留言

Devs.tw 是讓工程師寫筆記、網誌的平台。隨手紀錄、寫作,方便日後搜尋!

歡迎您一起加入寫作與分享的行列!

查看所有文章