MySQL Query需要很长时间

时间:2014-12-09 21:49:32

标签: mysql

我在table1列上有两个表table2idid列是两个表中的主键。两个表的行数完全相同。

如果我运行此查询:

select id from table1 where column1 = 'x'

我在0.02秒内得到以下结果:1, 85279, 85290, 85301, 102683, 158543, 965139, 1036217, 1036218

如果我然后运行查询select * from table2 where id in (1, 85279, 85290, 85301, 102683, 158543, 965139, 1036217, 1036218),我会在0.03秒内获得非常快速的结果。

嗯,这就是我的问题:如果我运行查询:

select * from table2 where id in
(select id from table1 where column1 = 'x')

我在8,5秒内得到了结果!

问题是为什么?基本上我在两种情况下做同样的事情,所以它应该大多需要0.02 + 0.03秒,而不是8,5(170倍)。

JOI QUERY EXPLAIN:

id  select_type table   type    possible_keys   key     key_len     ref                 rows    Extra
1   SIMPLE      dw      ALL     PRIMARY         NULL    NULL        NULL                1037890 Using where
1   SIMPLE      dd      eq_ref  PRIMARY         PRIMARY 4           allexxgd_db1.dw.id  1

SHOW CREATE TABLE dedict

CREATE TABLE `dedict` (
 `senseid` varchar(255) NOT NULL,
 `languageIdentifier` tinyint(4) DEFAULT NULL,
 `partOfSpeech` varchar(255) DEFAULT NULL,
 `_index` int(11) DEFAULT NULL,
 `writtenText` longtext,
 `lexiconid` varchar(255) DEFAULT NULL,
 `id` int(11) NOT NULL AUTO_INCREMENT,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1053320 DEFAULT CHARSET=utf8

SHOW CREATE TABLE dedict_writtenform

CREATE TABLE `dedict_writtenform` (
 `id` int(11) NOT NULL,
 `writtenForm` varchar(255) CHARACTER SET utf8 DEFAULT NULL,
 `writtenFormLength` int(11) DEFAULT NULL,
 PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8

INITIAL QUERY - 需要大约8.5秒:

select * from dedict where id in (select id from dedict_writtenform where writtenform = 'Hallo')

加入查询 - 大约需要9.5秒:

select dw.writtenform, dd.writtenText from dedict_writtenform dw join dedict dd on dd.id = dw.id where dw.writtenform='hallo'

1 个答案:

答案 0 :(得分:0)

我将从join查询开始:

select dw.writtenform, dd.writtenText
from dedict_writtenform dw join
     dedict dd
     on dd.id = dw.id
where dw.writtenform = 'hallo';

在大多数情况下,此查询的最佳索引为dedict_writtenform(writtenform, id)dedict(id, writtenText)。创建这些索引并检查查询的性能。