我正在使用一个简单的左连接查询从两个单独的表中获取两行数据。它们都包含一个名为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行数据。
任何有关无效代码或更好解决方法的建议都将受到赞赏!
答案 0 :(得分:1)
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
答案 1 :(得分: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;
答案 2 :(得分:0)
当您从联接的右侧检查项目的值时,不需要LEFT JOIN。内部联接在这里也可以正常工作,可能会更快