我有两张table:表1:
CREATE TABLE `lk_transaction_types` (
`transactionTypeID` int(10) unsigned NOT NULL AUTO_INCREMENT,
`isActive` tinyint(2) unsigned NOT NULL,
`code` varchar(8) NOT NULL,
`description` varchar(150) NOT NULL,
`isInbound` tinyint(2) unsigned NOT NULL DEFAULT '1',
`isOutbound` tinyint(2) unsigned NOT NULL DEFAULT '1',
PRIMARY KEY (`transactionTypeID`)
) ENGINE=InnoDB AUTO_INCREMENT=32 DEFAULT CHARSET=utf8;
表2:
CREATE TABLE `ediLoad` (
`loadID` int(10) unsigned NOT NULL AUTO_INCREMENT,
`processID` int(10) unsigned NOT NULL,
`success` tinyint(2) unsigned NOT NULL DEFAULT '0',
`transactionTypeID` tinyint(2) unsigned DEFAULT NULL,
`escoID` int(10) unsigned DEFAULT NULL,
`ldcID` int(10) unsigned DEFAULT NULL,
`commodityType` tinyint(3) unsigned NOT NULL DEFAULT '0',
`filename` varchar(150) NOT NULL,
`loadDate` datetime NOT NULL,
`processed` tinyint(2) unsigned NOT NULL DEFAULT '0',
`processedDate` datetime DEFAULT NULL,
`dataApplied` tinyint(2) unsigned NOT NULL DEFAULT '0',
`dataAppliedDate` datetime DEFAULT NULL,
`errorID` tinyint(3) unsigned DEFAULT NULL,
`error` tinyint(2) unsigned DEFAULT '0',
`warning` tinyint(2) unsigned DEFAULT '0',
PRIMARY KEY (`loadID`),
KEY `idx_processID` (`processID`,`transactionTypeID`,`escoID`),
KEY `idx_escoID` (`escoID`),
KEY `idx_filename` (`success`,`filename`),
KEY `idx_bulk` (`processed`,`loadDate`),
KEY `idx_loadDate` (`loadDate`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=35086005 DEFAULT CHARSET=utf8;
尝试运行简单查询时,它没有使用lk\ U transaction\ U types表上的主键:
SELECT COUNT(0)
FROM edi.ediLoad l
INNER JOIN edi.lk_transaction_types lk
ON lk.transactionTypeID = l.transactionTypeID
WHERE l.escoID = 2
AND lk.isActive = 1
AND lk.isInbound = 1;
查询速度很慢。所以我跑去解释
EXPLAIN SELECT COUNT(0)
FROM edi.ediLoad l
INNER JOIN edi.lk_transaction_types lk
ON lk.transactionTypeID = l.transactionTypeID
WHERE l.escoID = 2
AND lk.isActive = 1
AND lk.isInbound = 1;
这是回报
id select_type table partitions type possible_keys key key_len ref rows filtered Extra
1 SIMPLE lk NULL ALL PRIMARY NULL NULL NULL 31 3.23 Using where
1 SIMPLE l NULL ref idx_escoID idx_escoID 5 const 71580 10.00 Using where
这看起来像是一个简单的查询,主键上只有一个连接。为什么不使用主键?我甚至尝试将“force index for join(primary)”添加到连接中,但它仍然不使用主键。任何帮助都会很好。谢谢!
1条答案
按热度按时间8qgya5xd1#
详细说明一下@uueerdo在上面的注解中所说的话:在这种情况下,mysql不能使用idx\u processid索引,因为transactiontypeid是索引中的第二列,第一列(processid)不是where语句的一部分。
如果您只添加了transactiontypeid的新键,则将使用它。
从https://dev.mysql.com/doc/refman/5.7/en/multiple-column-indexes.html:
mysql可以对测试索引中所有列的查询使用多个列索引,或者只测试第一列、前两列、前三列的查询,依此类推。如果在索引定义中按正确的顺序指定列,则单个组合索引可以加快对同一表的多种查询。