SQL - How to find the highest number in a column?

前端 未结 15 1023
借酒劲吻你
借酒劲吻你 2020-12-30 18:25

Let\'s say I have the following data in the Customers table: (nothing more)

ID   FirstName   LastName
-------------------------------
20   John        Macken         


        
15条回答
  •  -上瘾入骨i
    2020-12-30 19:10

    If you are using AUTOINCREMENT, use:

    SELECT LAST\_INSERT\_ID();
    

    Assumming that you are using Mysql: http://dev.mysql.com/doc/refman/5.0/en/example-auto-increment.html

    Postgres handles this similarly via the currval(sequence_name) function.

    Note that using MAX(ID) is not safe, unless you lock the table, since it's possible (in a simplified case) to have another insert that occurs before you call MAX(ID) and you lose the id of the first insert. The functions above are session based so if another session inserts you still get the ID that you inserted.

提交回复
热议问题