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

前端 未结 15 1022
借酒劲吻你
借酒劲吻你 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:11
    select max(id) from Customers 
    
    0 讨论(0)
  • 2020-12-30 19:13
    select max(id) from customers
    
    0 讨论(0)
  • 2020-12-30 19:19

    If you want to just select the id use select max(id) from customer.

    If you want to select the entire row then use a query like this:

    select c1.*
    from customer c1, (select max(id) as max_id from customer )c2 
    where c1.id=c2.max_id
    

    c2 is an alias for the new temporary table which contains max id. Then its cross product is taken with customer table to get the entire row.

    Here we are writing a query in the from clause, which can often be quite useful.

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

    You can do

    SELECT MAX(ID) FROM Customers;
    
    0 讨论(0)
  • 2020-12-30 19:24

    If you're talking MS SQL, here's the most efficient way. This retrieves the current identity seed from a table based on whatever column is the identity.

    select IDENT_CURRENT('TableName') as LastIdentity
    

    Using MAX(id) is more generic, but for example I have an table with 400 million rows that takes 2 minutes to get the MAX(id). IDENT_CURRENT is nearly instantaneous...

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

    To find the next (still not used) auto-increment, I am using this function for somewhat years now.

    public function getNewAI($table)
        {
            $newAI = false;
    
            $mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
            if(mysqli_connect_errno()) {
                echo "Failed to connect to MySQL: " . mysqli_connect_error();
            }
    
            $sql = "SHOW TABLE STATUS LIKE '".$table."'";
    
            $result = $mysqli->query($sql);
    
            if($result) {
                $row = $result->fetch_assoc();
    
                $newAI = $row['Auto_increment'];
            }
            $mysqli->close();
    
            return $newAI;
        }
    
    0 讨论(0)
提交回复
热议问题