GROUP BY查询优化

时间:2011-05-29 21:38:43

标签: mysql optimization

逗人,
我需要您的帮助来优化以下查询。我有两个表,一个用于存储书籍数据,第二个表用于将书籍映射到与之相关的标签。我想要计算每个类别中某个出版商有多少本书。这个查询完成了这项工作,但我需要优化它:

select count(book.id),publisher from book,tag where book.id=tag.book_id  AND publisher ='Addison-Wesley Professional' AND tag.name='PHP' group by category

explain的结果是

    id  select_type     table   type    possible_keys   key     key_len     ref     rows    Extra
1   SIMPLE  tag     ref     PRIMARY     PRIMARY     92  const   1   Using where; Using index; Using temporary; Using f...
1   SIMPLE  book    eq_ref  PRIMARY     PRIMARY     4   test.tag.book_id    1   Using where

表格是:

-- 
-- Table structure for table `book`
-- 

CREATE TABLE `book` (
  `id` int(11) NOT NULL auto_increment,
  `name` varchar(30) NOT NULL,
  `ISBN` varchar(10) NOT NULL,
  `category` varchar(30) NOT NULL,
  `publisher` varchar(30) NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ;

-- 
-- Dumping data for table `book`
-- 

INSERT INTO `book` VALUES (1, 'PHP and MySQL Web Development', '9780672329', 'Web Development', 'Addison-Wesley Professional');
INSERT INTO `book` VALUES (2, 'JavaScript Patterns', '0596806752', 'Web Development', 'O''Reilly Media');



-- 
-- Table structure for table `tag`
-- 

CREATE TABLE `tag` (
  `name` varchar(30) NOT NULL,
  `book_id` int(11) NOT NULL,
  PRIMARY KEY  (`name`,`book_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

-- 
-- Dumping data for table `tag`
-- 

INSERT INTO `tag` VALUES ('MySQL', 1);
INSERT INTO `tag` VALUES ('PHP', 1);

1 个答案:

答案 0 :(得分:2)

您需要在图书表中按照确切的顺序对(发布商,类别)进行综合索引,因此对类别进行分组的子查询可以快速限制具有确切发布者的结果,然后使用索引的第二部分进行分组在类别上。

ALTER TABLE book ADD INDEX publ_cat( publisher, category );