加入表并找到min / max(Collection)

时间:2017-09-14 11:40:37

标签: mysql select join hql

我有一个结构:

public class ChosenCourseDate {

    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    @JoinColumn(name="chosencoursedate_id")
    List<ChosenCourseDatePeriod> chosenCourseDatePeriod;
}

public class ChosenCourseDatePeriod {

    Date startDateTime;
    Date endDateTime;

    @ManyToOne
    @JoinColumn(name="chosencoursedate_id")
    ChosenCourseDate chosenCourseDate;
}

我想在现有的select语句中添加一个新条件,以便在ChosenCourseDatePeriod中按最早的startDateTime查找对象。

1)选择声明:

select registration from CourseRegistration registration
left join registration.chosenCourseDate as chosencoursedate
left join chosencoursedate.chosenCourseDatePeriod as period
where registration.candidate =:candidate
and registration.course =:course
and min(period.startDateTime) >=:now;

结果:

  

无效使用群组功能

2)选择声明:

select registration, min(period.startDateTime) as earliestDate from CourseRegistration registration
left join registration.chosenCourseDate as chosencoursedate
left join chosencoursedate.chosenCourseDatePeriod as period
where registration.candidate =:candidate
and registration.course =:course
and earliestDate >=:now;

结果:

  

未知专栏&#39;最早日期&#39; in&#39; where子句&#39;,原因:null

3)我决定使用2 SELECT个语句,它有所帮助。

select registration from CourseRegistration registration
    left join registration.chosenCourseDate as chosencoursedate
    where registration.candidate =:candidate
    and registration.course =:course
    and (SELECT min(period.startDateTime) FROM ChosenCourseDate inChosenCourseDate join inChosenCourseDate.chosenCourseDatePeriod period where inChosenCourseDate = chosenCourseDate) >=:now;

我的第一个和第二个解决方案有什么问题?是否可以只做一个SELECT

1 个答案:

答案 0 :(得分:1)

您不能在WHERE子句上使用聚合函数,也不能使用GROUP BY子句。如果要检查最大日期,请添加GROUP BY子句并使用HAVING了解聚合函数的条件:

SELECT registration
FROM CourseRegistration registration
LEFT JOIN registration.chosenCourseDate chosencoursedate
LEFT JOIN chosencoursedate.chosenCourseDatePeriod period
WHERE registration.candidate =:candidate
  AND registration.course =:course
GROUP BY registration
HAVING min(period.startDateTime) >=:now;

您的第二个查询也是无效的,它只适用于旧版本的MySQL,因为您缺少GROUP BY子句。另一个原因是 - 您不能在创建它的同一层中使用派生列(由您制作的列),因此解决方案是使用另一个选择包装它:

SELECT * FROM ( Your query... ) // It is not available inside the query
WHERE earliestDate>=:now; // It is now available