我有一个存储学生ID、类别和生效日期(以及其他信息)的表格。日期可以是过去、现在或未来。我需要查询从表格中提取学生当前状态的结果。
以下查询可行:
SELECT *
FROM pupil_status
WHERE (status_pupil_id, status_date) IN (
SELECT status_pupil_id, MAX(status_date)
FROM pupil_status
WHERE status_date < NOW() -- to ensure we ignore the "future status"
GROUP BY status_pupil_id );
在MySQL中,表格的定义如下:
CREATE TABLE IF NOT EXISTS `pupil_status` (
`status_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`status_pupil_id` int(10) unsigned NOT NULL, -- a foreign key
`status_category_id` int(10) unsigned NOT NULL, -- a foreign key
`status_date` datetime NOT NULL, -- effective date/time of status change
`status_modify` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`status_staff_id` int(10) unsigned NOT NULL, -- a foreign key
`status_notes` text NOT NULL, -- notes detailing the reason for status change
PRIMARY KEY (`status_id`),
KEY `status_pupil_id` (`status_pupil_id`,`status_category_id`),
KEY `status_pupil_id_2` (`status_pupil_id`,`status_date`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1409 ;
然而,当学生人数达到950人,表中状态数超过1400时,该查询需要0.185秒才能处理。现在也许还可以接受,但当表格膨胀时,我担心可扩展性。生产系统可能会有超过10000名学生,每个学生都有15-20个状态。是否有更好的方法来编写此查询?是否有更好的索引可帮助查询?请告诉我。