首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >mysql:为什么左连接不使用索引?

mysql:为什么左连接不使用索引?
EN

Stack Overflow用户
提问于 2013-09-06 22:32:58
回答 1查看 19.1K关注 0票数 22

我正面临着一个奇怪的mysql查询性能问题。

SELECT
`pricemaster_products`.*,
`products`.*
FROM `pricemaster_products`
LEFT JOIN `products`
ON `pricemaster_products`.`ean` = `products`.`products_ean`

我明确地想要使用左连接。但是查询花费的时间比它应该花费的时间要多得多。

我尝试将连接更改为内连接。现在的查询速度非常快,但结果并不是我所需要的。

我使用了explain并得出了以下结论:

如果我使用"LEFT JOIN“,那么查询的EXPLAIN结果是...

type: "ALL"
possible_keys: NULL
key: NULL
key_len: NULL
ref: NULL
rows: 90.000 / 50.000 (the full number of the corresponding table)

..。用于两个表。

如果我使用“内连接”,那么EXPLAIN会给出:

表"products":

Same result as above.

对于表"pricemaster_products":

type: "ref"
possible_keys: "ean"
key: ean
key_len: 767
ref: func
rows: 1
extra: using where

两个表都在相关列上设置了索引。我能想到的左连接如此慢的唯一可能的原因是它根本不使用索引。但它为什么不会呢?

表结构如下:

CREATE TABLE IF NOT EXISTS `pricemaster_products` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `provider` varchar(255) CHARACTER SET utf8 NOT NULL,
  `ean` varchar(255) CHARACTER SET utf8 NOT NULL,
  `title` varchar(255) CHARACTER SET utf8 NOT NULL,
  `gnp` double DEFAULT NULL,
  `vat` int(11) DEFAULT NULL,
  `cheapest_price_with_shipping` double DEFAULT NULL,
  `last_cheapest_price_update` int(11) DEFAULT NULL,
  `active` tinyint(1) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`),
  KEY `ean` (`ean`),
  KEY `title` (`title`),
  KEY `gnp` (`gnp`),
  KEY `vat` (`vat`),
  KEY `provider` (`provider`),
  KEY `cheapest_price_with_shipping` (`cheapest_price_with_shipping`),
  KEY `last_cheapest_price_update` (`last_cheapest_price_update`),
  KEY `active` (`active`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=58436 ;

CREATE TABLE IF NOT EXISTS `products` (
  `products_id` int(11) NOT NULL AUTO_INCREMENT,
  `products_ean` varchar(128) DEFAULT NULL,
  `products_status` tinyint(1) NOT NULL DEFAULT '1',
  [a lot more of fields with no connection to the query in question]
  PRIMARY KEY (`products_id`),
  KEY `products_status` (`products_status`),
  KEY `products_ean` (`products_ean`),
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=105518 ;
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-09-06 23:07:52

连接的两个相关字段的类型不完全相同(使用字符集utf8的varchar(255)和使用latin1的varchar(128) )。我确实将两者设置为相同的长度和字符集,现在使用LEFT JOIN的查询可以正常工作。

票数 61
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18660252

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档