【问题标题】:postgreSQL query - find next lessonpostgreSQL 查询 - 查找下一课
【发布时间】:2021-04-07 09:05:28
【问题描述】:

我正在尝试编写一个 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

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

【问题讨论】:

    标签: sql postgresql datetime left-join greatest-n-per-group


    【解决方案1】:

    一个选项使用横向连接:

    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
    

    【讨论】:

    • 如何判断哪个选项更有效?
    • @WarMachine68:最好的选择可能是在您的数据库上测试这两个查询,看看哪个表现最好。
    猜你喜欢
    • 2014-06-14
    • 2022-12-15
    • 1970-01-01
    • 2023-02-23
    • 2010-09-29
    • 2021-09-24
    • 2017-04-06
    • 1970-01-01
    • 2022-10-02
    相关资源
    最近更新 更多