[英]Optimizing slow query in MySql InnoDB Database
我有一個運行速度非常慢的查詢的MySql數據庫。 我正在盡力使它性能更好,但看不到我在做什么錯。 也許你可以?
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
如果tablea.d = 100給出了1500行並且(tablea.d = tableb.d OR tableb.d = 1)給出了1600行,那么該查詢將花費大約10秒鍾來運行。 這似乎真的很慢。 我需要加快速度,但看不到我在做什么錯。
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
如果我不為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)
嘗試使用各種索引(使用EXPLAIN
)。 d
字段(兩個表中)的索引將有所幫助。 也許更多的是(d,c)
的索引。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.