我有这种结构的表格:
CREATE TABLE `supplies` (
`cycle_id` int(11) NOT NULL,
`subject_id` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
`market_id` int(11) NOT NULL,
`price` int(11) NOT NULL,
`currency_id` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
`offered_order` bigint(20) DEFAULT NULL,
PRIMARY KEY (`subject_id`,`market_id`,`cycle_id`,`price`),
KEY `fk_supplies_subjects` (`subject_id`),
KEY `fk_supplies_markets` (`market_id`),
KEY `fk_supplies_currencies` (`currency_id`),
CONSTRAINT `fk_supplies_currencies` FOREIGN KEY (`currency_id`) REFERENCES `currencies` (`currency_id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_supplies_subjects` FOREIGN KEY (`subject_id`) REFERENCES `subjects` (`subject_id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_supplies_markets` FOREIGN KEY (`market_id`) REFERENCES `markets` (`market_id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
表有大约20,000行。我的表现有问题。我正在记录需要很长时间的SQL查询,并且从日志中我可以看到:
将INSERT
放慢到表格中。
INSERT INTO supplies VALUES (11, 'userName', 18, 30, 'pound', 20) ;
从表
中缓慢DELETE
DELETE FROM supplies WHERE cycle_id = 6 AND market_id = 18 AND subject_id = 'userName' ;
我可以改善什么?
我想,更改索引会有所帮助,因为PRIMARY
键由4列组成(有些甚至是varchars
)。但是我该如何更改索引呢?
谢谢大家。
答案 0 :(得分:1)
您应该只使用一个字段创建主键。这是一项基本的性能优化
CREATE TABLE `supplies` (
`supplies_id` int(11) NOT NULL AUTO_INCREMENT,
`cycle_id` int(11) NOT NULL,
`subject_id` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
`market_id` int(11) NOT NULL,
`price` int(11) NOT NULL,
`currency_id` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
`offered_order` bigint(20) DEFAULT NULL,
PRIMARY KEY (`supplies_id`),
INDEX `index` (`subject_id` ASC,`market_id` ASC,`cycle_id` ASC,`price` ASC))
KEY `fk_supplies_subjects` (`subject_id`),
KEY `fk_supplies_markets` (`market_id`),
KEY `fk_supplies_currencies` (`currency_id`),
CONSTRAINT `fk_supplies_currencies` FOREIGN KEY (`currency_id`) REFERENCES `currencies` (`currency_id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_supplies_subjects` FOREIGN KEY (`subject_id`) REFERENCES `subjects` (`subject_id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_supplies_markets` FOREIGN KEY (`market_id`) REFERENCES `markets` (`market_id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
另一种可能的改进可以是删除级联约束。检查它们是否真的有必要。