2013-03-18 182 views
1

我用一個簡單的左聯接查詢從兩個獨立的表獲取數據的兩行。他們都持有一個名爲domain公共列,我加入他們此列計算基於一個表的訪問和其他表盈利值。慢MySQL查詢JOIN

SELECT t1.`domain` AS `domain`, 
     (SUM(earnings)/SUM(visits)) AS `rpv` 
FROM hat_adsense_stats t1 
LEFT JOIN hat_analytics_stats t4 ON t4.`domain`=t1.`domain` 
WHERE(t1.`hat_analytics_id`='91' OR t1.`hat_analytics_id`='92') 
     AND t1.`date`>='2013-02-18' 
     AND t4.`date`>='2013-02-18' 
GROUP BY t1.`domain` 
ORDER BY rpv DESC 
LIMIT 10; 

這是我運行的查詢,它需要9.060秒執行。

hat_adsense_stats表包含60887條記錄 的hat_analytics_stats表包含190780條記錄

而是由domain分組返回186行的數據,需要進行比較。

在高效的代碼或更好的方法來解決這個任何建議將不勝感激!

+0

顯示解釋查詢結果.. – divyabharathi 2013-03-18 09:07:47

回答

0

更改您這樣的查詢

SELECT 
    t1.`domain`   AS `domain`, 
    t2.earnings/t2.visits AS `rpv` 
FROM hat_adsense_stats t1 
    INNER JOIN (SELECT 
       domain, 
       sum(earnings)   AS earnings, 
       SUM(visits)   AS visits 
      FROM hat_adsense_stats 
      GROUP BY domain) AS t2 
    on t2.domain = t1.domain 
    LEFT JOIN hat_analytics_stats t4 
    ON t4.`domain` = t1.`domain` 
WHERE t1.`hat_analytics_id` IN('91','92') 
    AND t1.`date` >= '2013-02-18' 
    AND t4.`date` >= '2013-02-18' 
GROUP BY t1.`domain` 
ORDER BY rpv DESC 
LIMIT 10; 
0

的LEFT JOIN是不必要的,因爲你的加入右側選中一個項目的價值。內連接會工作得很好這裏很可能是開門更快

1

感謝raheel,這到底是什麼工作,與0.051sec一個執行時間。 :)

SELECT 
    t1.`domain` AS `domain`, 
    SUM(earnings)/visits AS `rpv` 
FROM hat_adsense_stats t1 
    INNER JOIN (SELECT 
     domain, 
     SUM(visits) AS visits 
     FROM hat_analytics_stats 
     WHERE `date` >= "2013-02-18" 
     GROUP BY domain) AS t4 
    ON t4.domain = t1.domain 
WHERE t1.`hat_analytics_id` IN('91','92') 
AND t1.`date`>='2013-02-18' 
GROUP BY t1.`domain` 
ORDER BY rpv DESC 
LIMIT 10