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

前端 未结 15 1060
借酒劲吻你
借酒劲吻你 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条回答
  •  孤独总比滥情好
    2020-12-30 19:05

    If you're not using auto-incrementing fields, you can achieve a similar result with something like the following:

    insert into Customers (ID, FirstName, LastName)
        select max(ID)+1, 'Barack', 'Obama' from Customers;
    

    This will ensure there's no chance of a race condition which could be caused by someone else inserting into the table between your extraction of the maximum ID and your insertion of the new record.

    This is using standard SQL, there are no doubt better ways to achieve it with specific DBMS' but they're not necessarily portable (something we take very seriously in our shop).

提交回复
热议问题