SQLAlchemy: show only latest result if a join returns multiple results

后端 未结 1 1116
旧巷少年郎
旧巷少年郎 2020-12-12 06:52

I\'m trying to create a Flask app that shows the latest score from individual players. So a player can have multiple scores, but on the leaderboard I only want to show her m

相关标签:
1条回答
  • 2020-12-12 07:28

    You can use the DISTINCT ON ... ORDER BY "idiom" in Postgresql to get the greatest-n-per-group, where n equals 1, given that your table isn't huge:

    players_with_score = db.session.query(Player, Score).\
        join(Score).\
        distinct(Player.id).\
        order_by(Player.id, Score.timestamp.desc())
    

    Since Score.timestamp is not nullable, you do not need to worry about descending order and NULLs.

    0 讨论(0)
提交回复
热议问题