gpt4 book ai didi

MySQL 从连接表中选择最大日期

转载 作者:行者123 更新时间:2023-11-29 01:30:16 24 4
gpt4 key购买 nike

我有这个 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_id 上可以有多个 student_startdatestudent_enddate 但我想选择每个学生 MAX(student_enddate)

如何做到这一点?

最佳答案

按如下方式修改您的子查询:

(
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
)
)

关于MySQL 从连接表中选择最大日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15922371/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com