我有一个查询,它对具有特定条件的表执行计数操作。我预计使用索引足以加快查询速度,但 EXPLAIN ANALYZE 的输出表明即使条件中使用的列上有索引,也会执行全表扫描。
这是查询和 EXPLAIN ANALYZE 输出:
EXPLAIN ANALYZE
SELECT COUNT(*) AS total
FROM galleries
WHERE school_id = 3451;
EXPLAIN ANALYZE
输出为:
Aggregate: count(0) (cost=29900.41 rows=21745) (actual time=63.052..63.052 rows=1 loops=1)
-> Filter: (galleries.school_id = 3451) (cost=27725.92 rows=21745) (actual time=50.530..63.026 rows=28 loops=1)
-> Covering index scan on galleries using idx_school_id (cost=27725.92 rows=217449) (actual time=0.047..45.998 rows=197797 loops=1)
尽管使用了索引扫描,但我没有看到预期的性能改进。为什么会发生这种情况,如何提高查询性能?
她是餐桌信息
CREATE TABLE `galleries` (
`id` int unsigned NOT NULL AUTO_INCREMENT,
`video_id` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
`file_name` varchar(191) DEFAULT NULL,
`school_id` varchar(191) DEFAULT NULL,
`type` varchar(20) DEFAULT NULL,
`file_type` varchar(20) DEFAULT NULL,
`meta` text,
`file_status` tinyint(1) DEFAULT '0',
`is_processed` tinyint(1) DEFAULT '0',
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`original_name` varchar(191) DEFAULT NULL,
`creator_id` int DEFAULT NULL,
`video_size` double(8,2) NOT NULL DEFAULT '0.00',
`available_resolutions` text,
`upload_by` varchar(20) DEFAULT NULL,
`length` int DEFAULT '0',
`parent_id` int unsigned NOT NULL DEFAULT '0',
`is_folder` tinyint(1) NOT NULL DEFAULT '0',
`is_deleted` timestamp NULL DEFAULT NULL,
`captions` text,
`drm_meta` text,
`drm_video_id` varchar(191) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `idx_video_id` (`video_id`),
KEY `idx_school_id` (`school_id`)
) ENGINE=InnoDB AUTO_INCREMENT=200396 DEFAULT CHARSET=utf8mb3
好吧,问题是我的学校 ID 不小心是 varchar,当我将其更改为 int 时,它工作得很好..