2
我有一个MySql数据库,运行速度非常慢。我尽我所能,使其表现更好,但无法看到我在这里做错了什么。也许你可以?在MySql InnoDB数据库中优化慢查询
CREATE TABLE `tablea` (
`a` int(11) NOT NULL auto_increment,
`d` mediumint(9) default NULL,
`c` int(11) default NULL,
PRIMARY KEY (`a`),
KEY `d` USING BTREE (`d`)
) ENGINE=InnoDB AUTO_INCREMENT=1867710 DEFAULT CHARSET=utf8;
CREATE TABLE `tableb` (
`b` int(11) NOT NULL auto_increment,
`d` mediumint(9) default '1',
`c` int(10) NOT NULL,
`e` mediumint(9) default NULL,
PRIMARY KEY (`b`),
KEY `c` (`c`),
KEY `d` (`d`),
) ENGINE=InnoDB AUTO_INCREMENT=848150 DEFAULT CHARSET=utf8;
查询:
SELECT tablea.a, tableb.e
FROM tablea
INNER JOIN tableb ON (tablea.c=tableb.c) AND (tablea.d=tableb.d OR tableb.d=1)
WHERE tablea.d=100
此查询需要像10秒运行,如果tablea.d = 100给出1500行和(tablea.d = tableb.d OR tableb.d = 1)给1600行。这似乎很慢。我需要做得更快,但我不明白我做错了什么。
MySQL的EXPLAIN输出:
id select_type table type possible_keys key key_len ref rows Extra
1 SIMPLE tablea ref d d 4 const 1092 Using where
1 SIMPLE tableb ref c,d c 4 tablea.c 1 Using where
看c,d上的复合指数是否有帮助。为什么OR tableb.d = 1 - imho会损害性能,请尝试使用union? – 2011-08-22 11:58:34