如何为此MySql查询设置正确的索引?

时间:2012-02-29 10:36:48

标签: mysql optimization select join indexing

我在MySql慢查询日志中显示此查询。 (它并不慢,但它没有正确使用索引)。我需要一些关于如何正确设置索引的帮助。

SELECT tbladded.amount*SUM(tbladdeditem.amount)
FROM tbladded
INNER JOIN tbladdeditem ON tbladded.addedid = tbladdeditem.addedid AND tbladdeditem.deleted='False' 
WHERE tbladded.userid=100
AND tbladded.date='2012-01-01'
AND tbladded.deleted='False'
GROUP BY tbladded.addedid


id  select_type  table         type  possible_keys        key          key_len  ref               rows  Extra
1   SIMPLE       tbladded      ref   PRIMARY,userid_date  userid_date  8        const,const       1     Using where
1   SIMPLE       tbladdeditem  ref   addedid              addedid      5        tbladded.addedid  1     Using where

这就是表格的样子:

CREATE TABLE `tbladded` (
    `addedid` int(11) NOT NULL AUTO_INCREMENT,
    `amount` double DEFAULT NULL,
    `date` date DEFAULT NULL,
    `userid` mediumint(9) DEFAULT NULL,
    `deleted` enum('False','True') CHARACTER SET latin1 DEFAULT 'False',
    PRIMARY KEY (`addedid`),
    KEY `userid_date` (`userid`,`date`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `tbladdeditem` (
    `addeditemid` int(11) NOT NULL AUTO_INCREMENT,
    `amount` double DEFAULT NULL,
    `addedid` int(11) DEFAULT NULL,
    `userid` mediumint(9) DEFAULT NULL,
    `deleted` enum('False','True') CHARACTER SET latin1 DEFAULT 'False',
    PRIMARY KEY (`addeditemid`),
    KEY `addedid` (`addedid`),
    KEY `userid` (`userid`),
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

1 个答案:

答案 0 :(得分:1)

试试这个:

ALTER TABLE `tbladded` ADD INDEX 
`tbladdedIndex` (`userid`, `date`, `deleted`);