Mysql分组查询时间最近的一条数据

需求描述

现有图书馆借书记录表如下:需要分组查询每个学生最近一次借书的记录

student_id(学号) student_name(姓名) book_name (书名) borrow_time (借书时间) predict_return_date(预计归还日期) actual_return_time (实际归还时间) 202201 张三 三国演义 2023-01-01 10:12:56 2023-01-15 2023-01-08 09:13:55 202302 李四 水浒传 2023-01-02 10:12:56 2023-01-16 2023-01-16 15:16:12 202301 张三 西游记 2023-01-10 10:12:56 2023-01-20 2023-01-20 11:23:56
借书记录表(borrow_books_record)

解决方案

    1.方法1,嵌套子查询
select *from  
    borrow_books_record br,

    (select student_id , max(borrow_time) as lastBorrowTime from borrow_books_record
     group by student_id) br1
where 
    br.student_id=br1.student_id and br.borrow_time = br1.lastBorrowTime 
group by br.student_id

执行这段sql语句,查询到的就是每个学生最近一次借书的数据。

    方法2 内连接+聚合函数
select 
   br.student_id,
   br.student_name,
   br.book_name,
   br.borrow_time,
   br.predict_return_date,
   br.actual_return_time
from 
   borrow_books_record br
   inner join(
         select student_id,max(borrow_time) as lastBorrowTime 
         from borrow_books_record
         group by student_id
         ) br1 on br1.student_id=br.student_id and br1.lastBorrowTime = br.borrow_time
经验分享 程序员 微信小程序 职场和发展