如果我理解您的问题,我认为不会发生这种情况。在下面,price_history 没有数据库引擎自动创建的重复索引。
create table A
( `product_id` INT NOT NULL,
`category_id` INT NOT NULL,
`priceitem_id` INT NOT NULL,
PRIMARY KEY (`product_id`, `category_id`, `priceitem_id`)
)ENGINE=INNODB;
CREATE TABLE IF NOT EXISTS `price_history` (
`amount` DECIMAL NULL,
`date_start` DATE NULL,
`date_end` DATE NULL,
`product_id` INT NOT NULL,
`category_id` INT NOT NULL,
`priceitem_id` INT NOT NULL,
PRIMARY KEY (`product_id`, `category_id`, `priceitem_id`),
FOREIGN KEY `f` (`product_id`, `category_id`, `priceitem_id`) references A(`product_id`, `category_id`, `priceitem_id`)
)ENGINE = InnoDB;
show create table price_history;
CREATE TABLE `price_history` (
`amount` decimal(10,0) DEFAULT NULL,
`date_start` date DEFAULT NULL,
`date_end` date DEFAULT NULL,
`product_id` int(11) NOT NULL,
`category_id` int(11) NOT NULL,
`priceitem_id` int(11) NOT NULL,
PRIMARY KEY (`product_id`,`category_id`,`priceitem_id`),
CONSTRAINT `price_history_ibfk_1` FOREIGN KEY (`product_id`, `category_id`, `priceitem_id`)
REFERENCES `a` (`product_id`, `category_id`, `priceitem_id`)
) ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS `price_history` (
`amount` DECIMAL NULL,
`date_start` DATE NULL,
`date_end` DATE NULL,
`product_id` INT NOT NULL,
`category_id` INT NOT NULL,
`priceitem_id` INT NOT NULL,
PRIMARY KEY (`product_id`, `category_id`, `priceitem_id`),
FOREIGN KEY `f` (`product_id`, `category_id`, `priceitem_id`) references A(`product_id`, `category_id`, `priceitem_id`)
)ENGINE = InnoDB;
show create table A;
CREATE TABLE `a` (
`product_id` int(11) NOT NULL,
`category_id` int(11) NOT NULL,
`priceitem_id` int(11) NOT NULL,
PRIMARY KEY (`product_id`,`category_id`,`priceitem_id`)
) ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS `price_historyBBB` (
id int auto_increment primary key,
`amount` DECIMAL NULL,
`date_start` DATE NULL,
`date_end` DATE NULL,
`product_id` INT NOT NULL,
`category_id` INT NOT NULL,
`priceitem_id` INT NOT NULL,
FOREIGN KEY `g` (`product_id`, `category_id`, `priceitem_id`) references A(`product_id`, `category_id`, `priceitem_id`)
)ENGINE = InnoDB;
show create table price_historyBBB;
CREATE TABLE `price_historybbb` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`amount` decimal(10,0) DEFAULT NULL,
`date_start` date DEFAULT NULL,
`date_end` date DEFAULT NULL,
`product_id` int(11) NOT NULL,
`category_id` int(11) NOT NULL,
`priceitem_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `g` (`product_id`,`category_id`,`priceitem_id`),
CONSTRAINT `price_historybbb_ibfk_1` FOREIGN KEY (`product_id`, `category_id`, `priceitem_id`)
REFERENCES `a` (`product_id`, `category_id`, `priceitem_id`)
) ENGINE=InnoDB;
show indexes from price_history;
show indexes from price_historyBBB;
因此,如果存在足够的键(例如,复合)最左边的块足以重用,那么 db 引擎将不会自动创建 Helper 索引。
例如,如果您有一个由 (col1,col2,col3,col5) 组合而成的键(PK 或其他),并且您的 FK 要求使用 (col1,col2),那么新索引不是自动生成。
如果需要 FK 是为了 (colX,col1,col2) 那么上面的 (col1,col2,col3,col5) 没有用(最左边的优先级)并且 db 引擎将需要创建一个 FK 助手索引。