需求分析: 有時候我們有這樣的需求,需要根據一個表中的某一字段進行分類,但是我們有想在分類后拿到分類后最新的記錄,如果直接用
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);
