简单:是什么让这个查询效率低下?

时间:2012-06-15 20:00:15

标签: mysql join indexing

SELECT 
    t1.`id` , 
    t1.`some_key` ,  
    t1.`date` ,
    t2.`data`
FROM `table1` AS `t1`
    LEFT JOIN `table2` AS `t2` ON t2.`id` = t1.`some_key`
WHERE DATE( t1.`date` ) = DATE( NOW( ) )

我正在尝试搜索今天添加的table1中的所有记录。我不知道记录的数量。我尝试在日期列中添加一个INDEX但是我的EXPLAIN仍然显示MySQL搜索table1中的所有n行。

编辑:::按要求解释

id  select_type     table   type    possible_keys   key     key_len     ref     rows    Extra 
1   PRIMARY     <derived2>  ALL     NULL    NULL    NULL    NULL    4   
1   PRIMARY     t2  eq_ref  PRIMARY     PRIMARY     4   t1.some_key     1   
2   DERIVED     table2  ALL     indx    NULL    NULL    NULL    5   Using where

2 个答案:

答案 0 :(得分:6)

你正在对t1.date进行转型;你失去了索引的好处,因为现在你的查询需要查看每一列。可以索引t1.date,但不是DATE(t1.date)。

答案 1 :(得分:1)

尝试重构查询

SELECT 
    t1.`id` , 
    t1.`some_key` ,  
    t1.`date` ,
    t2.`data`
FROM 
    (
        SELECT * FROM `table1`
        WHERE `date` >= (DATE(NOW()) + INTERVAL 0 SECOND)
    ) AS `t1`
    LEFT JOIN `table2` AS `t2`
    ON t2.`id` = t1.`some_key`
;

表达式(DATE(NOW()) + INTERVAL 0 SECOND)今天是午夜

mysql> select (DATE(NOW()) + INTERVAL 0 SECOND);
+-----------------------------------+
| (DATE(NOW()) + INTERVAL 0 SECOND) |
+-----------------------------------+
| 2012-06-15 00:00:00               |
+-----------------------------------+
1 row in set (0.00 sec)

mysql>

这是第二次尝试

SELECT 
    t1.`id` , 
    t1.`some_key` ,  
    t1.`date` ,
    t2.`data`
FROM 
    (
        SELECT id,somekey FROM `table1`
        WHERE `date` >= (DATE(NOW()) + INTERVAL 0 SECOND)
    ) AS t1
    INNER JOIN `table2` AS `t2` ON t1.`some_key` = t2.`id`;
;

请确保table1具有(date,id,somekey)索引

ALTER TABLE table1 ADD INDEX date_id_somekey_index (`date`,id,somekey);

子查询是索引上的纯范围扫描,NO TABLE ACCESS !!!

我还将LEFT JOIN更改为INNER JOIN。

至少要调查子查询单独运行:

SELECT id,somekey FROM `table1`
WHERE `date` >= (DATE(NOW()) + INTERVAL 0 SECOND);

此子查询仅生成今天的t1

条目