加快mysql查询速度

时间:2012-01-07 02:28:32

标签: mysql

我有两张桌子。一个是点击日志,记录我们收到点击的确切时间。第二个是美元/天表,记录我们每天通过特定网站获得的金额。

我需要计算每个网站的每日每次点击费用。下面的查询正在运行,但需要将近一分钟。

以下是解释结果:

id  select_type     table           type    possible_keys       key     key_len     ref     rows       Extra
1   SIMPLE          click_log       ALL     url_id,click_time   NULL    NULL        NULL    1404209    Using where; Using temporary; Using filesort
1   SIMPLE          daily_dollars   ref     url_id,date         date    3           func    6          Using where

查询:

SELECT date( click_log.click_time ) AS DAY,
       click_log.shorturl AS site,
       daily_dollars.money AS earned,
       count( click_log.click_id ) AS clicks,
       daily_dollars.money / count( click_log.click_id ) AS CPC
FROM `yourls_log` AS click_log, yourls_url_money AS daily_dollars
WHERE click_log.click_time >= "2011-07-01"
    AND click_log.url_id = daily_dollars.url_id
    AND date( click_log.click_time ) = daily_dollars.date
GROUP BY DAY , click_log.shorturl

我能做些什么来加快这个速度?

表格结构:

yourls_log
----------
click_id
click_time
shorturl
url_id

yourls_url_money
----------------
id
url_id
date
money

3 个答案:

答案 0 :(得分:0)

如果您在DBMS下创建了一个视图,然后查询该视图,则该过程应该更快地完成分配。这主要是因为视图是已经收集的数据,而不是从偏移量中查询数据。

另外请查看您的服务器统计信息,可能是负载太大了?

答案 1 :(得分:0)

我认为这就是你想要的:

SELECT DISTINCT date( click_log.click_time ) AS DAY,
   click_log.shorturl AS site,
   daily_dollars.money AS earned,
   count( click_log.click_id ) AS clicks,
   daily_dollars.money / count( click_log.click_id ) AS CPC
FROM `yourls_log` AS click_log, yourls_url_money AS daily_dollars
WHERE click_log.click_time >= "2011-07-01"
AND click_log.url_id = daily_dollars.url_id
AND date( click_log.click_time ) = daily_dollars.date
ORDER BY DAY , click_log.shorturl

答案 2 :(得分:0)

不确定原因,但速度要快得多(1.5秒):

SELECT m.date, c.shorturl, m.money, c.clicks, m.money / c.clicks AS CPC
FROM yourls_url_money AS m
LEFT JOIN (

SELECT date( click_time ) AS
DAY , url_id, shorturl, count( click_id ) AS clicks
FROM yourls_log
WHERE click_time >= "2011-07-01"
GROUP BY DAY , url_id, shorturl
) AS c ON m.url_id = c.url_id
AND m.date = c.day
WHERE date >= "2011-07-01"