我真的在努力处理以下两个问题。我有两张表,都有超过一百万条记录。第一个查询运行30秒,第二个运行超过7分钟。
基本上我想根据Lot获得count class.id和scan_layers.id。最有效的方法是什么?
选择count(class.id),count(scan_layers.id),Lot,从类左侧验证连接scan_layers on(class.ScanLayer = scan_layers.id)按批次分组;
选择count(class.id),count(distinct scan_layers.id),Lot,从类左侧验证加入scan_layers on(class.ScanLayer = scan_layers.id)按批次分组;
正如我解释的那样,他们都给了我相同的解释。
+----+-------------+--------------------+--------+---------------+------------------------+---------+----------------------------------+---------+----------------------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+--------------------+--------+---------------+------------------------+---------+----------------------------------+---------+----------------------------------------------+
| 1 | SIMPLE | class | index | NULL | defects_scan_layers_fk | 4 | NULL | 4417159 | Using index; Using temporary; Using filesort |
| 1 | SIMPLE | scan_layers | eq_ref | PRIMARY | PRIMARY | 4 | cdb.class.ScanLayer | 1 | |
+----+-------------+--------------------+--------+---------------+------------------------+---------+----------------------------------+---------+----------------------------------------------+
CREATE TABLE `class` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`ScanLayer` int(10) unsigned NOT NULL,
`Type` enum('Regular','Critical') NOT NULL DEFAULT 'Regular',
PRIMARY KEY (`id`),
UNIQUE KEY `Defect_UNIQUE` (`ScanLayer`),
KEY `class_scan_layers_fk` (`ScanLayer`),
CONSTRAINT `class_scan_layers_fk` FOREIGN KEY (`ScanLayer`) REFERENCES `scan_layers` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB
CREATE TABLE `scan_layers` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`LayerInfo` int(10) unsigned NOT NULL,
`Lot` varchar(45) NOT NULL DEFAULT 'DEFAULT',
`PhysicalID` int(10) unsigned NOT NULL,
`Scanned` datetime DEFAULT NULL,
`ScannedMachine` int(10) unsigned DEFAULT NULL,
`DefectsCount` int(10) unsigned NOT NULL DEFAULT '0',
`MovesCount` int(10) unsigned NOT NULL DEFAULT '0',
`Verified` datetime DEFAULT NULL,
`VerifiedMachine` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `ScanLayer_UNIQUE` (`LayerInfo`,`Lot`,`PhysicalID`),
KEY `scan_layers_layer_infos_fk` (`LayerInfo`),
KEY `scan_layers_scanned_machines_fk` (`ScannedMachine`),
KEY `scan_layers_verified_machines_fk` (`VerifiedMachine`),
KEY `scan_layers_verified` (`Verified`),
KEY `scan_layers_lot` (`Lot`),
CONSTRAINT `scan_layers_layer_infos_fk` FOREIGN KEY (`LayerInfo`) REFERENCES `layer_infos` (`id`) ON UPDATE CASCADE,
CONSTRAINT `scan_layers_scanned_machines_fk` FOREIGN KEY (`ScannedMachine`) REFERENCES `machines` (`id`) ON UPDATE CASCADE,
CONSTRAINT `scan_layers_verified_machines_fk` FOREIGN KEY (`VerifiedMachine`) REFERENCES `machines` (`id`) ON UPDATE CASCADE,
) ENGINE=InnoDB
非常感谢!