MySQL查询响应耗时太长

时间:2015-07-02 13:48:08

标签: php mysql

我目前正在对一个大型数据库进行一些MySQL查询,这个数据库需要很长时间才能回复(每次10分钟)。我理解查询很复杂,但我确实需要时间快速切换,因为它在脚本(PHP)等待响应时暂停所有其他进程。

这是当前的查询(对MySQL来说仍然是新的,所以我确信还有很多需要改进的地方):

SELECT DISTINCT username FROM `saved_users`
    WHERE referral_from IN(SELECT DISTINCT `referral`
                           FROM accounts 
                           WHERE owner = '{$owner}'
                           AND `use` = '1') 
    AND username NOT IN(SELECT username FROM `signup_history` 
                        WHERE owner = '{$owner}') 
    ORDER BY date_added DESC, 
             user_type = 'mod' DESC, 
             scrape_type = DESC 
    LIMIT {$limit} 

感谢所有建议。

编辑:EXPLAIN返回了这个:

1 PRIMARY saved_users ALL NULL NULL NULL NULL 49101 Using where; Using temporary; Using filesort 
3 DEPENDENT SUBQUERY signup_history ALL NULL NULL NULL NULL 59229 Using where 
2 DEPENDENT SUBQUERY accounts ALL NULL NULL NULL NULL 38 Using where; Using temporary

1 个答案:

答案 0 :(得分:1)

我猜username users中的EXISTS是唯一的。此外,通常最好使用NOT EXISTS / IN而不是NOT IN / SELECT su.username FROM saved_users su WHERE EXISTS (SELECT 1 FROM accounts WHERE r.referral = su.referral_from AND owner = '{$owner}' AND `use` = '1' ) AND NOT EXISTS (SELECT 1 FROM `signup_history` sh WHERE su.username = sh.username AND sh.owner = '{$owner}' ) ORDER BY date_added DESC, user_type = 'mod' DESC, scrape_type DESC LIMIT {$limit} ; 。所以,我首先将查询重写为:

users(date_added, user_type, scrape_type, user_name)

对于此查询,我建议使用以下索引:referrals(referral, owner, use)signup_history(username, owner)pointStart