MySQL左外连接很慢

时间:2011-01-13 19:47:38

标签: sql mysql performance

希望得到一些关于这个查询的帮助,我已经在它上面工作了一段时间,并且无法更快地得到它:

SELECT date, count(id) as 'visits' FROM dates 
LEFT OUTER JOIN visits 
ON (dates.date = DATE(visits.start) and account_id = 40 ) 
WHERE date >= '2010-12-13' AND date <= '2011-1-13' 
GROUP BY date ORDER BY date ASC

该查询大约需要8秒才能运行。我在dates.date,visits.start,visits.account_id和visits.start + visits.account_id上添加了索引,无法让它更快地运行。

表结构(仅显示访问表中的相关列):

create table visits (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `account_id` int(11) NOT NULL,
    `start` DATETIME NOT NULL,
    `end` DATETIME NULL,
    PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

CREATE TABLE `dates` (
  `date` date NOT NULL,
  PRIMARY KEY (`date`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

日期表包含2010-1-1至2020-1-1(~3k行)的所有日期。访问表包含从2010年6月1日到昨天的约400k行。我正在使用日期表,因此连接将在没有访问的情况下返回0次访问。

结果我想参考:

+------------+--------+
| date       | visits |
+------------+--------+
| 2010-12-13 |    301 |
| 2010-12-14 |    356 |
| 2010-12-15 |    423 |
| 2010-12-16 |    332 |
| 2010-12-17 |    346 |
| 2010-12-18 |    226 |
| 2010-12-19 |    213 |
| 2010-12-20 |    311 |
| 2010-12-21 |    273 |
| 2010-12-22 |    286 |
| 2010-12-23 |    241 |
| 2010-12-24 |    149 |
| 2010-12-25 |    102 |
| 2010-12-26 |    174 |
| 2010-12-27 |    258 |
| 2010-12-28 |    348 |
| 2010-12-29 |    392 |
| 2010-12-30 |    395 |
| 2010-12-31 |    278 |
| 2011-01-01 |    241 |
| 2011-01-02 |    295 |
| 2011-01-03 |    369 |
| 2011-01-04 |    438 |
| 2011-01-05 |    393 |
| 2011-01-06 |    368 |
| 2011-01-07 |    435 |
| 2011-01-08 |    313 |
| 2011-01-09 |    250 |
| 2011-01-10 |    345 |
| 2011-01-11 |    387 |
| 2011-01-12 |      0 |
| 2011-01-13 |      0 |
+------------+--------+

提前感谢您的帮助!

3 个答案:

答案 0 :(得分:4)

你的问题在这里:

ON (dates.date = DATE(visits.start) and account_id = 40 ) 

因为您在DATE上使用visits.start函数,所以MySQL无法使用索引进行连接。

最好的解决方案可能是在start_date表中添加end_datedates列并为这些列编制索引。因此,对于日期为2011-01-01的行,开始日期为2011-01-01 00:00:00,结束日期为2011-01-01 23:59:59。

然后你可以像这样直接加入日期表:

SELECT date, count(id) as 'visits' FROM dates 
LEFT OUTER JOIN visits 
ON (visits.start BETWEEN dates.start_date AND dates.end_date and account_id = 40 ) 
WHERE date >= '2010-12-13' AND date <= '2011-1-13' 
GROUP BY date ORDER BY date ASC

另一种选择是在访问表上单独存储日期和时间部分,并仅使用日期部分加入。

答案 1 :(得分:0)

我认为由于DATE()函数,它主要是慢的。您可以向存储整个日期的Visits添加日期列,并编写触发器以在插入访问或更新其日期时自动更新它。这将允许MySQL更好地利用连接中使用的索引。

答案 2 :(得分:0)

这样的事情:从eumiro中选择结果的外连接?

SELECT date, v.visits as 'visits' FROM dates 
LEFT OUTER JOIN (SELECT DATE(start) as dt, count(id) as 'visits'
FROM visits 
WHERE account_id = 40
AND date BETWEEN '2010-12-13' AND '2011-01-13' 
GROUP BY DATE(start)
ORDER BY 1)
v
ON (dates.date = v.dt ) 
WHERE date >= '2010-12-13' AND date <= '2011-1-13' 

编辑:编辑过的SQL 编辑:另一个选项 - 内联选择,类似的东西:

SELECT date, (select count(*)  as 'visits' 
FROM  from visits 
where date = DATE(visits.start) and account_id = 40 ) 
) from dates
WHERE date >= '2010-12-13' AND date <= '2011-1-13' 
ORDER BY date ASC