mysql搜索范围内的min(日期)

时间:2016-05-13 08:46:32

标签: mysql min

我想在设定范围内找到最小日期,例如下面我想找到每个学生的最短申请日期。 MySQL不接受此查询。

SELECT MIN(applications.date) AS 'D', students.name
FROM applications, students
WHERE applications.student_id = students.id AND
D BETWEEN '2016-05-01' AND '2016-05-31'
GROUP BY students.id

2 个答案:

答案 0 :(得分:2)

试试这个,只需使用where子句中的表列而不是别名;)

SELECT *
FROM (
    SELECT MIN(applications.date) AS 'D', students.name
    FROM applications, students
    WHERE applications.student_id = students.id
    GROUP BY students.id
) tmp
WHERE D BETWEEN '2016-05-01' AND '2016-05-31'

答案 1 :(得分:0)

您不能使用where子句对来自min()的聚合函数的结果应用过滤器,而是可以使用having子句

SELECT MIN(a.date) AS `D`,s.id,s.name
FROM applications a
JOIN students s ON a.student_id = s.id 
GROUP BY s.id,s.name
HAVING `D` >= '2016-05-01' AND `D` <= '2016-05-31'