Mysql

優化 ORDER BY

  • December 20, 2021

我是 MySQL 新手,並編寫了以下查詢(見下文)。

問題: 查詢返回準確的數據,但執行大約需要 40 秒。但是,當我移除ORDER BY零件時,需要 0.06 秒。

我對每一ORDER BY列都有索引,但不確定還能做什麼。如果有人可以重寫/推薦更改,那將是非常有用的。

程式碼:

SELECT DISTINCT username
   FROM `users`
   WHERE `in_progress` = 0
     AND scraped_from IN
       (SELECT DISTINCT `username`
        FROM source_accounts
        WHERE group_users = 'New Users'
          AND (`type` = 'users' OR `type` = 'both')
          AND `use` = '1')
     AND username NOT IN
       (SELECT user_tofollow
        FROM `follow_history`
        WHERE owner_account = 'admin')
   ORDER BY real_user DESC,
            IF((last_used) IS NULL,'0','1'),
            IF((last_update)>3,'1','0'),
            DATE(last_used),
            IF((user_ratio)>100,'1','0') LIMIT 1000;

解釋:

1   PRIMARY     scraped_users   ref     idx1,scraped_from,in_progress,username  in_progress     1   const   687025  Using where; Using temporary; Using filesort
1   PRIMARY     <subquery2>     eq_ref  <auto_key>  <auto_key>  767     userstack.users.scraped_from    1   Distinct
2   MATERIALIZED    source_accounts     ref     username,group_users,type,use   group_users     767     const   48  Using index condition; Using where; Distinct
3   DEPENDENT SUBQUERY  follow_history  index_subquery  user_tofollow   user_tofollow   767     func    1   Using where             

性能問題不在於ORDER BY, 本身…

NOT IN ( SELECT ... )優化不佳。這效果更好(如果在您的情況下可行): JOIN ... ON ... WHERE id IS NULL

如果無法做到這一點,那麼這可能會更好: NOT EXISTS ( SELECT * FROM ... )

確保您在嘗試排序的列上有索引。這是一個很好的參考:

https://dev.mysql.com/doc/refman/5.0/en/order-by-optimization.html

引用自:https://dba.stackexchange.com/questions/116830