[英]Optimizing slow query in MySql InnoDB Database
I have a MySql database with a query that is running really slow. 我有一个运行速度非常慢的查询的MySql数据库。 I'm trying the best I can to make it perform better but can't see what I'm doing wrong here.
我正在尽力使它性能更好,但看不到我在做什么错。 Maybe you can?
也许你可以?
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;
The query: 查询:
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
This query takes like 10 seconds to run if tablea.d=100 gives 1500 rows and (tablea.d=tableb.d OR tableb.d=1) gives 1600 rows. 如果tablea.d = 100给出了1500行并且(tablea.d = tableb.d OR tableb.d = 1)给出了1600行,那么该查询将花费大约10秒钟来运行。 This seems really slow.
这似乎真的很慢。 I need to make it much faster but I can't see what I'm doing wrong.
我需要加快速度,但看不到我在做什么错。
MySql EXPLAIN outputs: 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
If I am not confused by the OR
, the query is equivalent to: 如果我不为
OR
迷惑,则查询等同于:
SELECT tablea.a, tableb.e
FROM tablea
INNER JOIN tableb
ON tablea.c = tableb.c
WHERE tablea.d = 100
AND tableb.d IN (1,100)
Try it (using EXPLAIN
) with various indexes. 尝试使用各种索引(使用
EXPLAIN
)。 An index on the d
field (in both tables) would help. d
字段(两个表中)的索引将有所帮助。 Perhaps more, an index on (d,c)
. 也许更多的是
(d,c)
的索引。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.