0

Which is the best method for optimizing the select in select mysql query ?

This is my example:

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')

My database has over 500k entries.

4

3 回答 3

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就可以通过查找索引来确定它需要哪些行。

于 2013-01-10T23:23:48.190 回答
-1

请改用存在子句:

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')
于 2013-01-10T22:44:01.207 回答
-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';
于 2013-01-10T22:44:08.383 回答