2012-08-10 168 views
0

有人可以幫我這個查詢嗎?它工作正常,但需要太多時間。我確定這個問題是tb_activities中的OR語句太多。有沒有人有任何想法使這個查詢更快?我怎樣才能加快這個MySQL查詢

SELECT tb_posts.* 
FROM tb_posts 
WHERE EXISTS (SELECT c_id 
       FROM tb_users 
       WHERE tb_posts.c_uid = tb_users.c_id 
         AND tb_users.c_tokens > 0) 
     AND NOT EXISTS (SELECT c_id 
         FROM tb_activities 
         WHERE tb_posts.c_url = tb_activities.c_url 
           AND tb_activities.c_category = 'gplus' 
           AND (tb_activities.c_uid LIKE '%,6x1,%' 
            OR tb_activities.c_uid LIKE '%,6x1' 
            OR tb_activities.c_uid LIKE '6x1,%' 
            OR tb_activities.c_uid = '6x1')) 
     AND NOT EXISTS (SELECT c_id 
         FROM tb_blacklist 
         WHERE tb_posts.c_url LIKE Concat('%', tb_blacklist.c_url 
                , '%') 
           AND tb_blacklist.c_times > 2 
           AND tb_blacklist.c_category = 'gplus') 
     AND tb_posts.c_category = 'classic' 
     AND tb_posts.c_status = 'run' 
     AND tb_posts.c_nogplus = 0 
GROUP BY tb_posts.c_url 
ORDER BY tb_posts.c_cost DESC, 
      tb_posts.c_date DESC 
LIMIT 30 
+0

索引...所有即時消息 – CheeseConQueso 2012-08-10 16:13:39

回答

1

我在這裏做的是重寫第一個WHERE EXISTS ...。爲什麼? Here就是答案。另一個有趣的閱讀是this。所以你可以考慮進一步重寫查詢。不幸的是我現在沒有更多的時間了。但主要性能提升您將通過添加(複合)索引無論如何得到。將索引放在JOIN所基於的列或WHERE子句中經常使用的列上。

SELECT tb_posts.* 
FROM tb_posts 
INNER JOIN tb_users ON tb_posts.c_uid = tb_users.c_id 
WHERE tb_users.c_tokens > 0 
     AND NOT EXISTS (SELECT c_id 
         FROM tb_activities 
         WHERE tb_posts.c_url = tb_activities.c_url 
           AND tb_activities.c_category = 'gplus' 
           AND (tb_activities.c_uid LIKE '%,6x1,%' 
            OR tb_activities.c_uid LIKE '%,6x1' 
            OR tb_activities.c_uid LIKE '6x1,%' 
            OR tb_activities.c_uid = '6x1')) 
     AND NOT EXISTS (SELECT c_id 
         FROM tb_blacklist 
         WHERE tb_posts.c_url LIKE Concat('%', tb_blacklist.c_url, '%') 
           AND tb_blacklist.c_times > 2 
           AND tb_blacklist.c_category = 'gplus') 
     AND tb_posts.c_category = 'classic' 
     AND tb_posts.c_status = 'run' 
     AND tb_posts.c_nogplus = 0 
GROUP BY tb_posts.c_url 
ORDER BY tb_posts.c_cost DESC, 
      tb_posts.c_date DESC 
LIMIT 30 

而且你可能想了解EXPLAIN,所以你知道使用哪些索引(或不使用)。

作爲一個旁註,彼得·凱斯關於改變WHERE條款順序的提示是無稽之談。查詢優化器無論如何處理這個。

相關問題