Finding the next available id in MySQL

前端 未结 15 1649
予麋鹿
予麋鹿 2020-11-29 00:50

I have to find the next available id (if there are 5 data in database, I have to get the next available insert place which is 6) in a MySQL database. How can I do that? I h

相关标签:
15条回答
  • 2020-11-29 01:35

    As I understand, if have id's: 1,2,4,5 it should return 3.

    SELECT t1.id + 1
    FROM theTable t1
    WHERE NOT EXISTS (
        SELECT * 
        FROM theTable t2
        WHERE t2.id = t1.id + 1
    )
    LIMIT 1
    
    0 讨论(0)
  • 2020-11-29 01:37

    If you want to select the first gap, use this:

    SELECT  @r
    FROM    (
            SELECT  @r := MIN(id) - 1
            FROM    t_source2
            ) vars,
            t_source2
    WHERE   (@r := @r + 1) <> id
    ORDER BY
            id
    LIMIT   1;
    

    There is an ANSI syntax version of the same query:

    SELECT  id
    FROM    mytable mo
    WHERE   (
            SELECT  id + 1
            FROM    mytable mi
            WHERE   mi.id < mo.id
            ORDER BY
                    mi.id DESC
            LIMIT 1
            ) <> id
    ORDER BY
            id,
    LIMIT   1
    

    however, it will be slow, due to optimizer bug in MySQL.

    0 讨论(0)
  • 2020-11-29 01:38

    The problem with many solutions is they only find the next "GAP", while ignoring if "1" is available, or if there aren't any rows they'll return NULL as the next "GAP".

    The following will not only find the next available gap, it'll also take into account if the first available number is 1:

    SELECT CASE WHEN MIN(MyID) IS NULL OR MIN(MyID)>1
    -- return 1 if it's available or if there are no rows yet
    THEN
        1
    ELSE -- find next gap
        (SELECT MIN(t.MyID)+1
        FROM MyTable t (updlock)
        WHERE NOT EXISTS (SELECT NULL FROM MyTable n WHERE n.MyID=t.MyID+1))
    END AS NextID
    FROM MyTable
    
    0 讨论(0)
  • 2020-11-29 01:42

    I don't think you can ever be sure on the next id, because someone might insert a new row just after you asked for the next id. You would at least need a transaction, and if I'm not mistaken you can only get the actual id used after inserting it, at least that is the common way of handling it -- see http://dev.mysql.com/doc/refman/5.0/en/getting-unique-id.html

    0 讨论(0)
  • 2020-11-29 01:47

    If this is used in conjunction for INSERTING a new record you could use something like this.

    (You've stated in your comments that the id is auto incrementing and the other table needs the next ID + 1)

    INSERT INTO TABLE2 (id, field1, field2, field3, etc) 
    VALUES(
       SELECT (MAX(id) + 1), field1, field2, field3, etc FROM TABLE1
       WHERE condition_here_if_needed
    )
    

    This is pseudocode but you get the idea

    0 讨论(0)
  • 2020-11-29 01:47
    <?php
    Class Database{
        public $db;
        public $host   = DB_HOST;
        public $user   = DB_USER;
        public $pass   = DB_PASS;
        public $dbname = DB_NAME;
    
        public $link;
        public $error;
    
        public function __construct(){
            $this->connectDB();
        }
        private function connectDB(){
        $this->link = new mysqli($this->host, $this->user, $this->pass, $this->dbname);
        if(!$this->link){
            $this->error ="Connection fail".$this->link->connect_error;
            return false;
        }
     }
    
        // Select or Read data
    
        public function select($query){
            $result = $this->link->query($query) or die($this->link->error.__LINE__);
            if($result->num_rows > 0){
                return $result;
            } else {
                return false;
            }
        }
    
    }
     $db = new Database();
    $query = "SELECT * FROM table_name WHERE id > '$current_postid' ORDER BY ID ASC LIMIT 1";
    $postid = $db->select($query);
    if ($postid) {
      while ($result = $postid->fetch_assoc()) { 
            echo $result['id'];
        } 
    
      } ?>
    
    0 讨论(0)
提交回复
热议问题