【发布时间】:2010-10-22 14:09:30
【问题描述】:
我有一个表,其中存储了一个学生 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 个状态。
有没有更好的方法来编写这个查询?我应该有更好的索引来协助查询吗?请告诉我。
【问题讨论】:
标签: mysql optimization