我有以下 MySQL 查询,它运行良好,但有时运行速度非常慢。
SELECT s.ID AS `Student_ID` , IFNULL( COUNT( f.ID ) , 0 ) AS `Flags` , IFNULL( COUNT( i.ID ) , 0 ) AS `Interventions`
FROM `frog_shared`.`student` s
LEFT JOIN `frog_flags`.`flags` f ON s.ID = f.`Student_ID`
LEFT JOIN `frog_flags`.`interventions` i ON s.ID = i.`Student_ID`
WHERE s.ID
IN ( 132336 )
GROUP BY s.ID
ORDER BY s.Surname ASC , s.Firstname DESC
基本上,给定一个学生 ID 列表,我希望我的系统返回Flags
他们收到的数量和Interventions
.
但是,当有大约 30 名学生的列表时,查询需要将近一秒钟的时间才能运行。
ed时的查询结果EXPLAIN
如下:
student.id
我在and上有索引flags.Student_ID
,所以我认为这不是问题。
我还能如何优化我的查询?
更新:SHOW CREATE
表格
CREATE TABLE `interventions` (
`ID` int(10) NOT NULL auto_increment,
`Visible` int(1) NOT NULL,
`Student_ID` int(6) NOT NULL COMMENT 'FK frog_shared.student',
`Staff_ID` int(6) NOT NULL COMMENT 'FK frog_shared.staff',
`Datetime` datetime NOT NULL,
`Category_ID` int(3) NOT NULL COMMENT 'FK intervention_categories',
`Generation_Type` varchar(1) NOT NULL COMMENT '[A]utomated or [M]anual',
`Reason` text NOT NULL,
`Status` varchar(1) NOT NULL COMMENT '[O]pen, In [P]rogress, [C]losed',
PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=latin1
CREATE TABLE `flags` (
`ID` int(10) NOT NULL auto_increment,
`Student_ID` int(6) NOT NULL COMMENT 'FK frog_shared.student',
`Staff_ID` int(6) NOT NULL COMMENT 'FK frog_shared.staff',
`Datetime` datetime NOT NULL,
`Period_ID` int(2) NOT NULL COMMENT 'FK frog_shared.periods',
`Location_ID` int(3) NOT NULL COMMENT 'FK frog_shared.locations',
`Category_ID` int(2) NOT NULL COMMENT 'FK flag_categories',
`Alert_ID` int(11) default NULL COMMENT 'FK frog_alerts.alerts',
`Action_Taken_Category_ID` int(1) default NULL COMMENT 'FK frog_flags.categories FA',
`Action_Taken_Status` varchar(1) default NULL COMMENT '[P]ending or [C]omplete',
`Details` text NOT NULL,
PRIMARY KEY (`ID`),
KEY `Student_ID` (`Student_ID`),
KEY `Staff_ID` (`Staff_ID`),
KEY `Datetime` (`Datetime`)
) ENGINE=InnoDB AUTO_INCREMENT=3669 DEFAULT CHARSET=latin1
CREATE TABLE `student` (
`id` varchar(20) default NULL,
`UPN` varchar(25) NOT NULL,
`Firstname` varchar(50) NOT NULL,
`Surname` varchar(50) NOT NULL,
`Year_Group` int(2) NOT NULL,
`Tutor_Group` varchar(15) NOT NULL,
`SEN_Status` varchar(1) default NULL,
`Flags` varchar(10) default NULL,
PRIMARY KEY (`UPN`),
KEY `id` (`id`),
KEY `Year_Group` (`Year_Group`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1