优化sql查询 - 在select中选择

时间:2013-01-10 22:35:06

标签: mysql

哪个是优化select mysql查询中select的最佳方法?

这是我的例子:

SELECT count(distinct email) 
FROM emails_stats 
WHERE DATE_FORMAT(time, '%Y-%m-%d') >= '2012-12-12' 
 and email in (SELECT email 
               FROM `reminder` 
               WHERE DATE_FORMAT(time, '%Y-%m-%d') = '2012-12-12')

我的数据库有超过500,000个条目。

3 个答案:

答案 0 :(得分:0)

SELECT count(distinct emails_stats.email) 
FROM emails_stats 
JOIN reminder ON emails_stats.email= reminder.email
WHERE 
    emails_stats.time >= CAST('2012-12-12 00:00:00' AS datetime) AND
    (reminder.time BETWEEN CAST('2012-12-12 00:00:00' AS datetime) AND CAST('2012-12-12 23:59:59' AS datetime));

如果对表字段使用date_format(),mysql将需要遍历表中的每一行,因为它需要获取该date_format()函数的结果才能将值与给定的字符串进行比较。为了加快速度,请为“时间”字段创建索引并改为使用此查询。这样mysql就可以通过查找索引来确定它需要哪些行。

答案 1 :(得分:-1)

改为使用exists子句:

SELECT count(distinct email) 
FROM emails_stats 
WHERE DATE_FORMAT(time, '%Y-%m-%d') >= '2012-12-12' 
and exists (SELECT 1
                   FROM `reminder` 
                   WHERE emails_stats.email = `reminder`.email 
                   and DATE_FORMAT(time, '%Y-%m-%d') = '2012-12-12')

答案 2 :(得分:-1)

最好的方法是在这里使用join

SELECT count(distinct emails_stats.email) 
FROM emails_stats 
JOIN reminder ON emails_stats.email= reminder.email
WHERE DATE_FORMAT(emails_stats.time, '%Y-%m-%d') >= '2012-12-12';