Bootstrap

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

需求描述

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

借书记录表(borrow_books_record)
student_id(学号)student_name(姓名)

book_name

(书名)

borrow_time

(借书时间)

predict_return_date(预计归还日期)

actual_return_time

(实际归还时间)

202201张三三国演义2023-01-01 10:12:562023-01-152023-01-08 09:13:55
202302李四水浒传2023-01-02 10:12:562023-01-162023-01-16 15:16:12
202301张三西游记2023-01-10 10:12:562023-01-202023-01-20 11:23:56

解决方案

  • 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

;