内部连接0846秒的慢mysql查询

时间:2014-09-28 16:39:51

标签: mysql inner-join performance

当我使用INNER JOIN

查询时,我有另一个问题

此查询

SELECT *
FROM `engine4_product_file` INNER JOIN
     `engine4_file`
     ON engine4_product_file.fid = engine4_file.id
WHERE engine4_product_file.pid IN (3347,3346,3345,3343,3342,3337) and
      engine4_file.active = 1 AND
      engine4_file.ext IN ('jpg','gif','png','jpeg')

并创建表engine4_product_file

 CREATE TABLE `engine4_product_file` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `fid` int(11) NOT NULL,
  `pid` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `engine4_product_file` (`fid`),
  KEY `pid` (`pid`)
) ENGINE=InnoDB AUTO_INCREMENT=6549 DEFAULT CHARSET=latin1

并创建表engine4_file

CREATE TABLE `engine4_file` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `uid` int(11) NOT NULL,
  `name` longtext CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
  `url` longtext CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
  `date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `active` int(11) NOT NULL DEFAULT '1',
  `size` int(11) DEFAULT NULL,
  `ext` varchar(10) DEFAULT NULL,
  `folder` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=48801 DEFAULT CHARSET=latin1

这个解释

id  select_type     table   type    possible_keys   key     key_len     ref     rows    Extra   
1   SIMPLE  engine4_product_file    range   engine4_product_file,pid    pid     4   NULL    30  Using where
1   SIMPLE  engine4_file    eq_ref  PRIMARY     PRIMARY     4   akafine_social2.engine4_product_file.fid    1   Using where

1 个答案:

答案 0 :(得分:0)

更改您的WHERE条件

  WHERE  engine4_file.active = 1 AND
         engine4_file.ext IN ('jpg','gif','png','jpeg') AND
  engine4_product_file.pid IN (3347,3346,3345,3343,3342,3337) 

添加索引

 ALTER TABLE engine4_file ADD KEY (active,ext)