PostgreSQL - fetch the row which has the Max value for a column

前端 未结 9 854
感动是毒
感动是毒 2020-11-28 18:38

I\'m dealing with a Postgres table (called \"lives\") that contains records with columns for time_stamp, usr_id, transaction_id, and lives_remaining. I need a query that wil

9条回答
  •  庸人自扰
    2020-11-28 19:16

    I think you've got one major problem here: there's no monotonically increasing "counter" to guarantee that a given row has happened later in time than another. Take this example:

    timestamp   lives_remaining   user_id   trans_id
    10:00       4                 3         5
    10:00       5                 3         6
    10:00       3                 3         1
    10:00       2                 3         2
    

    You cannot determine from this data which is the most recent entry. Is it the second one or the last one? There is no sort or max() function you can apply to any of this data to give you the correct answer.

    Increasing the resolution of the timestamp would be a huge help. Since the database engine serializes requests, with sufficient resolution you can guarantee that no two timestamps will be the same.

    Alternatively, use a trans_id that won't roll over for a very, very long time. Having a trans_id that rolls over means you can't tell (for the same timestamp) whether trans_id 6 is more recent than trans_id 1 unless you do some complicated math.

提交回复
热议问题