1. 程式人生 > >Mysql換種寫法速度提高10倍

Mysql換種寫法速度提高10倍

t_house 表有 4萬多條資料,現在僅僅只要查詢10條
原先的sql語句是:

 select h.*, u.* from t_house  h
    left join t_user u
    on u.id = h.user_id
    order by h.create_time desc 
    limit 0,10

時間是: 9.958s ,因為它要去 遍歷t_house表,雖然只查詢10條資料,但卻遍歷了4萬條

改進後的 sql語句:

 select h.*,u.* from 
    (
      select * from t_house 
      order by h.create_time desc 
      limit 0,10
    ) h
    left join t_user u 
    on u.id = h.user_id

時間是: 0.077s,這種寫法的關鍵在於: 先 查詢 t_house的10條資料,然後再去匹配 t_user 中的記錄。