MySQL自动增量无重复

时间:2015-07-13 23:26:10

标签: php mysql sql

如果我运行以下查询,然后使用AUTO_INCREMENT变量立即发布到table1,2个用户同时运行查询并获得相同的自动增量值的几率是多少?

这种情况不太可能发生吗?

$query = "SELECT AUTO_INCREMENT
              FROM  INFORMATION_SCHEMA.TABLES
              WHERE TABLE_SCHEMA = 'db1'
              AND   TABLE_NAME   = 'table1'";

$result =  $link->query($query);
$numRows = mysqli_num_rows($result);

while($var2 = mysqli_fetch_array($result)) {

   $autoIncr = $var2['AUTO_INCREMENT'];
}



$query = "INSERT INTO table1(id,firstName)
          VALUES('$autoIncr','$firstName')";

2 个答案:

答案 0 :(得分:2)

非常喜欢

create table table1
( 
  id int auto_increment primary key,
  fullName varchar(100) not null
);

然后在插入

insert table1 (fullName) values('Fred Smith');

答案 1 :(得分:0)

以下是我获得独特AI值的答案:

$query = "INSERT INTO table1(id,firstName)
          VALUES('','$firstName')";

$result =       $link->query($query);
$autoIncr =     $link->insert_id;   //Gets id of last inserted row