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

前端 未结 15 1020
借酒劲吻你
借酒劲吻你 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).

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

    To get it at any time, you can do SELECT MAX(Id) FROM Customers .

    In the procedure you add it in, however, you can also make use of SCOPE_IDENTITY -- to get the id last added by that procedure.
    This is safer, because it will guarantee you get your Id--just in case others are being added to the database at the same time.

    0 讨论(0)
  • 2020-12-30 19:07
    select * from tablename order by ID DESC
    

    that will give you row with id 22

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

    You can also use relational algebra. A bit lengthy procedure, but here it is just to understand how MAX() works:

    E := πID (Table_Name)
    E1 := πIDID >= ID' ((ρID' E) ⋈ E)) – πIDID < ID’ ((ρID' E) ⋈ E))

    Your answer: Table_Name ⋈ E1

    Basically what you do is subtract set of ordered relation(a,b) in which a<b from A where a, b ∈ A.

    For relation algebra symbols see: Relational algebra From Wikipedia

    0 讨论(0)
  • 2020-12-30 19:10
    SELECT * FROM Customers ORDER BY ID DESC LIMIT 1
    

    Then get the ID.

    0 讨论(0)
  • 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.

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