我有这个MySQL
查询:
SELECT
s.student_id,
s.student_firstname,
s.student_lastname,
sd.student_startdate,
sd.student_enddate,
s.isActive,
c.city_name,
ctc.category_name
FROM
students s
INNER JOIN
(SELECT sd1.student_id, sd1.student_startdate, sd1.student_enddate FROM studentdates sd1) sd ON sd.student_id = s.student_id
INNER JOIN
cityselections c ON c.city_id = s.student_city_id
INNER JOIN
coursecategory ctc ON s.student_course_category_id = ctc.category_id
WHERE
sd.student_enddate BETWEEN CURDATE() AND ADDDATE(CURDATE(), INTERVAL 14 DAY)
AND s.student_city_id NOT LIKE '1'
AND s.student_city_id = 18
AND s.isActive = 1
GROUP BY s.student_id
ORDER BY sd.student_enddate ASC , s.student_lastname , s.student_firstname
在表studentdates
中,每个student_startdate
上可以有多个student_enddate
和student_id
,但我想选择每个学生MAX(student_enddate)
。
如何做到这一点?
答案 0 :(得分:5)
修改子查询,如下所示:
(
SELECT
sd1.student_id, sd1.student_startdate, sd1.student_enddate
FROM (
SELECT student_id, MAX(student_enddate) AS enddate
FROM studentdates
GROUP BY student_id
) AS s_max_enddate
JOIN studentdates AS sd1 ON (
sd1.student_id = s_max_enddate.student_id
AND sd1.student_enddate = s_max_enddate.enddate
)
)