MySQL选择优化:解释选择行结果

时间:2016-03-22 03:37:08

标签: mysql select foreign-keys foreign-key-relationship explain

我有两个名为父和子的表。看起来像这样:

  parent{id, name}
  children{id, name, parent_id}

我在children表上设置了外键约束。并执行此查询:

  EXPLAIN Select child.name AS childname, par.name AS parentname
  FROM children AS child
  INNER JOIN parent AS par ON child.parent_id = par.id

结果显示父表的keyref列为NULL,rows为16007.这可以解释为什么简单查询执行的时间非常长。如果我在select子句上注释掉par.name,则查询会快速返回数据。问题的正确结果是keyref的值是否合适?我怎么能这样做?

以下是EXPLAIN

的实际表格

enter image description here

非常奇怪,因为我已经设置了必要的索引,并且EXPLAIN SELECT找不到外键的key

以下是实际的CREATE TABLES:

CREATE TABLE `am_asset_trx_voice` (
  `am_asset_trx_voice_id` BIGINT(20) NOT NULL AUTO_INCREMENT,
  `am_asset_id` INT(11) NOT NULL DEFAULT '0',
  `name` VARCHAR(255),
  `date_updated` TIMESTAMP NULL DEFAULT NULL,
  `created_by` VARCHAR(255) DEFAULT NULL,
  `updated_by` VARCHAR(255) DEFAULT NULL,
  PRIMARY KEY (`am_asset_trx_voice_id`,`am_asset_id`),
  KEY `fk_owned_by_id_voice` (`owned_by_id`),
  KEY `fk_bonded_id_voice` (`bonded_id`),
  KEY `fk_am_asset_id_voice` (`am_asset_id`),
  CONSTRAINT `fk_am_asset_id_voice` FOREIGN KEY (`am_asset_id`) REFERENCES `am_asset` (`id`),
  CONSTRAINT `fk_bonded_id_voice` FOREIGN KEY (`bonded_id`) REFERENCES `am_bonded_typedef` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `fk_owned_by_id_voice` FOREIGN KEY (`owned_by_id`) REFERENCES `am_owned_by_typedef` (`id`) ON UPDATE CASCADE
) ENGINE=INNODB AUTO_INCREMENT=14766 DEFAULT CHARSET=utf8;


CREATE TABLE `am_owned_by_typedef` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `description` varchar(255) DEFAULT NULL,
  `created_by` varchar(100) DEFAULT NULL,
  `date_created` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_by` varchar(100) DEFAULT NULL,
  `date_updated` timestamp NULL DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8

CREATE TABLE `am_bonded_typedef` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `description` varchar(255) DEFAULT NULL,
  `created_by` varchar(100) DEFAULT NULL,
  `date_created` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_by` varchar(100) DEFAULT NULL,
  `date_updated` timestamp NULL DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8

有没有我没看过的地方?有些角度我没看过?请帮忙。

0 个答案:

没有答案