可能是這樣的: -
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與成員加入(應對未經過培訓的成員)。
編輯 - 刪除子查詢並將它們放入視圖以允許主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;
您可以發佈sqlfiddle? –
當然,這裏你去: http://sqlfiddle.com/#!2/a1ec1/1 – Oxholm