1

我正在使用一个简单的左连接查询从两个单独的表中获取两行数据。他们都拥有一个名为的共同列domain,我将他们加入到这一列中,以根据一个表访问量和其他表收入来计算一个值。

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 行数据。

任何有关低效代码或解决此问题的更好方法的建议都将不胜感激!

4

3 回答 3

1

感谢 raheel 打开门,这最终奏效了,执行时间为 0.051 秒。:)

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
于 2013-03-18T10:08:51.233 回答
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;
于 2013-03-18T09:09:57.500 回答
0

LEFT JOIN 是不必要的,因为您从连接的右侧检查项目的值。INNER JOIN 在这里也可以工作,而且可能会更快

于 2013-03-18T09:11:42.890 回答