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

前端 未结 15 1021
借酒劲吻你
借酒劲吻你 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:25

    If you've just inserted a record into the Customers table and you need the value of the recently populated ID field, you can use the SCOPE_IDENTITY function. This is only useful when the INSERT has occurred within the same scope as the call to SCOPE_IDENTITY.

    INSERT INTO Customers(ID, FirstName, LastName)
    Values
    (23, 'Bob', 'Smith')
    
    SET @mostRecentId = SCOPE_IDENTITY()
    

    This may or may not be useful for you, but it's a good technique to be aware of. It will also work with auto-generated columns.

    0 讨论(0)
  • 2020-12-30 19:30

    Depends on what SQL implementation you are using. Both MySQL and SQLite, for example, have ways to get last insert id. In fact, if you're using PHP, there's even a nifty function for exactly that mysql_insert_id().

    You should probably look to use this MySQL feature instead of looking at all the rows just to get the biggest insert ID. If your table gets big, that could become very inefficient.

    0 讨论(0)
  • 2020-12-30 19:30

    In PHP:

    $sql = mysql_query("select id from customers order by id desc");
    $rs = mysql_fetch_array($sql);
    if ( !$rs ) { $newid = 1; } else { $newid = $rs[newid]+1; }
    

    thus $newid = 23 if last record in column id was 22.

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