修复使用索引,使用临时,使用filesort

时间:2014-04-22 19:55:40

标签: mysql sql join explain

我有这样的3张桌子。我试图左加入他们

    SELECT `t`.`title` AS `category_title`,`t`.`id` AS `category_id`, `st`.`title` AS
 `subcategory_title`, `st`.`id` AS `subcategory_id`, `st`.`parent_id` AS
 `subcategory_parent`, `n`.`title` AS `news_title`,`n`.`id` AS `news_id` FROM
`t_categories` `t` LEFT JOIN t_categories AS `st` ON `st`.`parent_id`=t.`id` LEFT JOIN
 t_newsrelations AS `nr` ON `nr`.`category_id`=st.`id` LEFT JOIN t_news AS `n` ON 
`n`.`id`=nr.`news_id` WHERE `t`.`enabled` = 1 AND `n`.`enabled` = 1 AND `n`.`type`!=1 AND
 `n`.`type`!=5 ORDER BY `t`.`position`,`st`.`position`,`n`.`position` ASC

这是表格的结构

    CREATE TABLE IF NOT EXISTS `t_categories` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `parent_id` int(11) NOT NULL,
  `title` tinytext NOT NULL,
  `position` tinyint(4) unsigned NOT NULL DEFAULT '0',
  `type` tinyint(1) unsigned NOT NULL,
  `enabled` tinyint(1) unsigned NOT NULL DEFAULT '1',
  UNIQUE KEY `id` (`id`),
  KEY `type` (`type`),
  KEY `parent_id` (`parent_id`),
  KEY `enabled` (`enabled`),
  KEY `id_parent_position_enabled` (`id`,`parent_id`,`position`,`enabled`),
  KEY `position` (`position`),
  KEY `parent_id_2` (`parent_id`,`enabled`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 ;


CREATE TABLE IF NOT EXISTS `t_news` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `title` tinytext NOT NULL,
  `m_title` tinytext NOT NULL,
  `url` varchar(2000) NOT NULL,
  `keywords` text NOT NULL,
  `description` text NOT NULL,
  `body` longtext NOT NULL,
  `position` tinyint(4) unsigned NOT NULL DEFAULT '0',
  `type` tinyint(1) unsigned NOT NULL,
  `city_id` int(4) NOT NULL,
  `quickmenu_enabled` tinyint(1) unsigned NOT NULL DEFAULT '0',
  `quickmenu` text NOT NULL,
  `enabled` tinyint(1) unsigned NOT NULL DEFAULT '1',
  PRIMARY KEY (`id`),
  UNIQUE KEY `id` (`id`),
  KEY `position` (`position`),
  KEY `type` (`type`),
  KEY `city_id` (`city_id`),
  KEY `url` (`url`(333)),
  KEY `quickmenu_enabled` (`quickmenu_enabled`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 ;


CREATE TABLE IF NOT EXISTS `t_newsrelations` (
  `category_id` int(11) NOT NULL,
  `news_id` int(11) unsigned NOT NULL,
  KEY `category_id` (`category_id`),
  KEY `news_id` (`news_id`),
  KEY `category_id_2` (`category_id`,`news_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

SELECT EXPLAIN显示我

explain-img t_newsrelations是中间表。表t_categories包含由parent_id列链接的类别和子类别。来自t_news的每个项目都可以是多个子类别的成员,这就是他们通过t_newsrelations链接的原因

如何优化查询?为什么它显示使用索引,使用临时,使用filesort?

1 个答案:

答案 0 :(得分:3)

ORDER BY `t`.`position`,`st`.`position`,`n`.`position` ASC

在给定您拥有的表的情况下,您无法消除此查询中的临时表和文件排序,因为您要对多个表中的列进行排序。优化排序意味着使用索引,以便查询按您希望的顺序获取行。但是在MySQL中没有办法创建一个跨越多个表的索引。

解决此问题的唯一方法是反规范化,直到所有三列都在一个表中,并在三列上创建一个索引。但非规范化有其自身的缺点。