postgreSQL 查询 - 查找下一课

postgreSQL query - find next lesson

我正在尝试编写一个 PostgreSQL 查询来列出月租费最低的两种仪器,并告知每个列出的仪器的下一课安排时间。我有这两张表:

//Table lesson
lesson_id | instrument_id | start
001       | 01            | 2021-01-01 10:00:00
002       | 01            | 2021-01-02 10:00:00
003       | 02            | 2021-01-04 10:00:00
004       | 02            | 2021-01-05 10:00:00

//Table instrument
instrument_id | fee_per_month
01            | 300
02            | 400
03            | 500

我想要:

instrument_id | fee_per_month | lesson_id | start
01            | 300           | 001       | 2021-01-01 10:00:00
02            | 400           | 003       | 2021-01-04 10:00:00

获得最低费用的两个工具已解决。如何以最低的费用获得这两种乐器的下一课?

一个选项使用横向连接:

select i.*, l.lesson_id, l.start
from instrument i
left join lateral (
    select l.*
    from lesson l
    where l.instrument_id = i.instrument_id and l.start >= current_date
    order by l.start
    limit 1
) l on true

这会为每种乐器(如果有)带来今天或今天之后的第一课。

您也可以使用 distinct on:

select distinct on (i.instrument_id) i.*, l.lesson_id, l.start
from instrument i
left join lesson l on l.instrument_id = i.instrument_id and l.start >= current_date
order by i.instrument_id, l.start