可能是这样的:-
SELECT m.member_id, Sub2.team_id, Sub2.MaxTrainingDate
FROM member m
LEFT OUTER JOIN
(
SELECT tm.member_id, t.team_id, Sub1.MaxTrainingDate
FROM training_member tm
INNER JOIN training t ON tm.training_id = t.training_id
INNER JOIN
(
SELECT tm.member_id, MAX(t.training_date) AS MaxTrainingDate
FROM training_member tm
LEFT OUTER JOIN training t ON tm.training_id = t.training_id
GROUP BY tm.member_id
) Sub1
ON Sub1.member_id = tm.member_id
AND Sub1.MaxTrainingDate = t.training_date
) Sub2
ON Sub2.member_id = m.member_id
ORDER BY m.member_name, MaxTrainingDate DESC
使用内部选择来获取每个成员的最新培训,将其与培训成员和培训表连接以获取其他详细信息(即 team_id),然后针对成员 LEFT JOIN(以应对未受过培训的成员)。
编辑 - 删除子查询并将它们放入视图以允许主 SQL 成为视图。
查看以获取每个成员的最大培训日期
CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `vw_max_training` AS select `tm`.`member_id` AS `member_id`,max(`t`.`training_date`) AS `MaxTrainingDate` from (`training_member` `tm` left join `training` `t` on((`tm`.`training_id` = `t`.`training_id`))) group by `tm`.`member_id`;
查看以获取每个成员的最大培训日期的团队详细信息
CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `vw_max_training_team` AS select `tm`.`member_id` AS `member_id`,`t`.`team_id` AS `team_id`,`sub1`.`MaxTrainingDate` AS `MaxTrainingDate` from ((`training_member` `tm` join `training` `t` on((`tm`.`training_id` = `t`.`training_id`))) join `vw_max_training` `sub1` on(((`sub1`.`member_id` = `tm`.`member_id`) and (`sub1`.`MaxTrainingDate` = `t`.`training_date`))));
最终视图
CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `vw_main` AS select `m`.`member_id` AS `member_id`,`sub2`.`team_id` AS `team_id`,`sub2`.`MaxTrainingDate` AS `MaxTrainingDate` from (`member` `m` left join `vw_max_training_team` `sub2` on((`sub2`.`member_id` = `m`.`member_id`))) order by `m`.`member_name`,`sub2`.`MaxTrainingDate` desc;