MySQL 为mysql表设置自动增量初始值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7557856/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
set auto increment initial value for mysql table
提问by Lucas
I'm trying to create a table in my sql using PHP but I'm not sure how to set an initial value for the auto increment field.
我正在尝试使用 PHP 在我的 sql 中创建一个表,但我不确定如何为自动增量字段设置初始值。
This is what i have so far:
这是我到目前为止:
function create_table($db_host,$db_user,$db_pswrd,$db_name){
$connect = mysql_connect($db_host,$db_user,$db_pswrd) or die(mysql_error());
mysql_select_db($db_name, $connect);
$sql = "CREATE TABLE MY_TABLE
(
table_id int NOT NULL AUTO_INCREMENT,
PRIMARY KEY(table_id),
table_1 varchar(45),
table_2 varchar(45),
table_3 varchar(999),
table_4 varchar(45)
)"or die(mysql_error());
mysql_query($sql,$connect)or die(mysql_error());
mysql_close($connect);
}
So i need to know how to set the initial Auto Increment value on this table, upon creation?
所以我需要知道如何在创建时在这个表上设置初始自动增量值?
Thanks
谢谢
回答by Lucas
If you don't have the auto-increment column in the table yet:
如果表中还没有自动递增列:
$sql = "ALTER TABLE MY_TABLE ADD id INT UNSIGNED NOT NULL AUTO_INCREMENT,
ADD INDEX (id);";
Then to set the auto-increment starting value:
然后设置自动增量起始值:
$sql = "ALTER TABLE MY_TABLE AUTO_INCREMENT = 111111;";
Potential duplicate of this post.
此帖子的潜在副本。
回答by Matthieu Napoli
Assuming your auto increment column is the first one:
假设您的自动增量列是第一个:
$sql = "CREATE TABLE MY_TABLE
(
table_1 INT AUTO_INCREMENT,
table_2 varchar(45),
table_3 varchar(999),
table_4 varchar(45)
) AUTO_INCREMENT = 231";
The starting value will be, here, 231.
此处的起始值为 231。
I changed the column type to INT
, because you can't use a VARCHAR
for auto-increment.
我将列类型更改为INT
,因为您不能将 aVARCHAR
用于自动增量。
(and remove the or die(mysql_error())
on this line btw, its pointless because it's just a variable creation, not a SQL query being executed)
(or die(mysql_error())
顺便说一句,删除这一行,它毫无意义,因为它只是一个变量创建,而不是正在执行的 SQL 查询)