mysql 左连接 怎么走索引_mysql:为什么左连接不使用索引?

在尝试使用LEFT JOIN进行查询时,发现性能较慢,即便两个表的相关列都设置了索引。当切换到INNER JOIN时,查询速度显著提升,但结果不符合需求。通过EXPLAIN分析,LEFT JOIN查询类型为'ALL',未使用索引,而INNER JOIN则使用了'ean'的索引。表结构显示两个表都有ean列的索引,但LEFT JOIN为何不使用成为疑问。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我遇到了一个mysql查询的奇怪性能问题 .

SELECT

`pricemaster_products`.*,

`products`.*

FROM `pricemaster_products`

LEFT JOIN `products`

ON `pricemaster_products`.`ean` = `products`.`products_ean`

我明确地想要使用左连接 . 但是查询需要花费更多的时间 .

我试图将连接更改为INNER JOIN . 查询现在非常快,但结果不是我需要的 .

我用了解释并得出以下结论:

如果我使用“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)

......对于两张 table .

如果我使用“INNER JOIN”,那么EXPLAIN会给出:

对于表“产品”:

Same result as above.

对于表“pricemaster_products”:

type: "ref"

possible_keys: "ean"

key: ean

key_len: 767

ref: func

rows: 1

extra: using where

两个表都在相关列上设置了索引 . 我认为LEFT JOIN如此缓慢的唯一可能原因是根本不使用索引 . 但为什么不呢?

表结构如下:

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 ;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值