如何优化这个mysql查询 - 解释输出包括在内

时间:2010-06-22 08:06:16

标签: mysql optimization join indexing explain

这是查询(基本上是基于标签的搜索查询): -

select
SUM(DISTINCT(ttagrels.id_tag in (2105,2120,2151,2026,2046) )) as key_1_total_matches, td.*, u.* 
from Tutors_Tag_Relations AS ttagrels
Join Tutor_Details AS td ON td.id_tutor = ttagrels.id_tutor
JOIN Users as u on u.id_user = td.id_user 
where  (ttagrels.id_tag in (2105,2120,2151,2026,2046)) group by td.id_tutor HAVING key_1_total_matches = 1

以下是执行此查询所需的数据库转储: -

CREATE TABLE IF NOT EXISTS `Users` (
  `id_user` int(10) unsigned NOT NULL auto_increment,
  `id_group` int(11) NOT NULL default '0',

  PRIMARY KEY  (`id_user`),
  KEY `Users_FKIndex1` (`id_group`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=730 ;

INSERT INTO `Users` (`id_user`, `id_group`) VALUES
(303, 1);


CREATE TABLE IF NOT EXISTS `Tutor_Details` (
  `id_tutor` int(10) unsigned NOT NULL auto_increment,
  `id_user` int(10) NOT NULL default '0',

  PRIMARY KEY  (`id_tutor`),
  KEY `Users_FKIndex1` (`id_user`),
  KEY `id_user` (`id_user`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=58 ;

INSERT INTO `Tutor_Details` (`id_tutor`, `id_user`) VALUES
(26, 303);


CREATE TABLE IF NOT EXISTS `Tags` (
  `id_tag` int(10) unsigned NOT NULL auto_increment,
  `tag` varchar(255) default NULL,
  PRIMARY KEY  (`id_tag`),
  UNIQUE KEY `tag` (`tag`),
  KEY `id_tag` (`id_tag`),
  KEY `tag_2` (`tag`),
  KEY `tag_3` (`tag`),
  KEY `tag_4` (`tag`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2957 ;


INSERT INTO `Tags` (`id_tag`, `tag`) VALUES
(2026, 'Brendan.\nIn'),
(2046, 'Brendan.'),
(2105, 'Brendan'),
(2120, 'Brendan''s'),
(2151, 'Brendan)');


CREATE TABLE IF NOT EXISTS `Tutors_Tag_Relations` (
  `id_tag` int(10) unsigned NOT NULL default '0',
  `id_tutor` int(10) unsigned default NULL,
  `tutor_field` varchar(255) default NULL,
  `cdate` timestamp NOT NULL default CURRENT_TIMESTAMP,
  `udate` timestamp NULL default NULL,
  KEY `Tutors_Tag_Relations` (`id_tag`),
  KEY `id_tutor` (`id_tutor`),
  KEY `id_tag` (`id_tag`),
  KEY `id_tutor_2` (`id_tutor`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `Tutors_Tag_Relations` (`id_tag`, `id_tutor`, `tutor_field`, `cdate`, `udate`) VALUES
(2105, 26, 'firstname', '2010-06-17 17:08:45', NULL);

ALTER TABLE `Tutors_Tag_Relations`
  ADD CONSTRAINT `Tutors_Tag_Relations_ibfk_2` FOREIGN KEY (`id_tutor`) REFERENCES `Tutor_Details` (`id_tutor`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  ADD CONSTRAINT `Tutors_Tag_Relations_ibfk_1` FOREIGN KEY (`id_tag`) REFERENCES `Tags` (`id_tag`) ON DELETE NO ACTION ON UPDATE NO ACTION;

查询的作用是什么? 这个查询实际上搜索包含“Brendan”(作为他们的名字或传记或其他东西)的导师。 id_tags 2105,2120,2151,2026,2046只是喜欢“%Brendan%”的标签。

我的问题是: -

1.在此查询的说明中,引用列显示ttagrels为NULL,但有可能的键(Tutors_Tag_Relations,id_tutor,id_tag,id_tutor_2)。那么,为什么没有采取任何关键。如何使查询参考。有可能吗? 2.另外两个表td和u正在使用引用。那些需要的索引?我想不是。

在此查看解释查询输出 http://www.test.examvillage.com/explain.png

1 个答案:

答案 0 :(得分:0)

不要用表中的单个记录分析数据库的性能。创建至少100条记录。