提问者:小点点

获取记录与它绑定最后一条记录具有特定值


其中有2个表:

例如书

id || --
1  || 
2  || 
3  || 

和贷款:

id | booId  | duration
1  | 1      | 4
2  | 1      | 6
3  | 1      | **5 (last one for book1)**
4  | 2      | 2
5  | 2      | 3
6  | 3      | 8
7  | 3      | **(5 not the last one so i don't need book3)**
8  | 3      | 6
9  | 2      |  **5 (last one for book2)**

我需要获得所有的图书id,其中最后的贷款期限等于,所以在本例中它将是:[1,2]


共1个答案

匿名用户

一种方法使用聚合:

select book_id
from loans l
group by book_id
having max(id) = max(case when duration = 5 then id end);

这将检查给定图书的最后一个id是否与所需持续时间的给定图书的最后一个id匹配。

相关问题