我在使用 MySQL 查询时遇到了速度问题。表定义如下:
CREATE TABLE IF NOT EXISTS `student` (
`student_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`forename` varchar(30) NOT NULL,
`updated_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`surname` varchar(50) NOT NULL,
`student_college` int(11) DEFAULT NULL,
`countup` smallint(5) unsigned DEFAULT NULL,
PRIMARY KEY (`student_id`),
KEY `countup` (`countup`),
KEY `student_sort` (`countup`,`updated_time`),
KEY `student_college` (`student_college`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
和
CREATE TABLE IF NOT EXISTS `college` (
`college_id` int(11) NOT NULL AUTO_INCREMENT,
`college_name` varchar(100) NOT NULL DEFAULT 'Centre Name',
`college_location` int(11) DEFAULT NULL,
PRIMARY KEY (`college_id`),
KEY `college_location` (`college_location`),
KEY `college_name` (`college_name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
查询如下:
SELECT *
FROM student
JOIN college ON student.student_college = college.college_id
WHERE
college_location = 1
ORDER BY student.countup desc, student.updated_time desc
LIMIT 15;
我得到以下解释:
id select_type table type possible_keys key key_len ref rows Extra
1 SIMPLE college ref "PRIMARY,college_location" college_location 5 const 915 Using where; Using temporary; Using filesort
1 SIMPLE student ref student_college student_college 5 speed_test.college.college_id 50 Using where
Student 表有大约 500,000 条记录,college 表有 915 行。第三张表用于保存学院的所有位置。我的查询需要检索特定位置的所有学生,然后按 countup 和 updated_time 对结果进行排序。我有一个关于 countup 和 updated_time 的复合索引。我想摆脱文件排序,但我找不到令人满意的方法。
我已经考虑将 移动college_location
到学生表中,以便可以将其组合成一个复合索引。有更好的解决方案吗?