需求分析: 有时候我们有这样的需求,需要根据一个表中的某一字段进行分类,但是我们有想在分类后拿到分类后最新的记录,如果直接用
group by来获取会发生sql错误
例如 这里有张学生表studentInfo,有字段: id(学号),name(姓名),age(年龄),class(班级),reportDate(报名时间)
我们需要查出每个班级最新报名的学生信息
错误的sql: select id,name,age,class,max(reportDate) from studentInfo group by class;
group by子句只能让我们查询类别分类后共有的属性,而个人的具体信息是不允许查询的
我们应该借助子查询,先将我们每个班最新的报名时间查询出来,再作为日期的条件查询主表
select * from studentInfo where reportDate in (select max(reportDate) from studentInfo group by reportDate);