2

我有这个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_startdatestudent_enddate每个student_id,但我想选择每个学生MAX(student_enddate)

如何才能做到这一点?

4

1 回答 1

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
    )
)
于 2013-04-10T09:53:45.377 回答