mysql创建,添加主键

primary key 

1、最简单的:

CREATE TABLE t1(
id int not null,
name char(20)
);

2、带主键的:

a:
CREATE TABLE t1(
id int not null primary key,
name char(20)
);

b:复合主键
CREATE TABLE t1(
id int not null,
name char(20),
primary key (id,name)
);

3、带默认值的:

CREATE TABLE t1(
id int not null default 0 primary key,
name char(20) default '1'
);
 
追问
我只想给之前的 一个尚未成为主键的 字段 成为  主键  ,  比如我有一个表 test, 里边有二个  字段  a   和  b  ,  我现在想让 a 成为 主键 ,代码是什么吗?    直接给我写可以吗?  谢谢谢谢!!!!!
 
追答
ALTER TALBE tb_name ADD PRIMARY KEY (列名);
alter table 表名 change name name 数据类型 primary key auto_increment;
ALTER TABLE test  ADD CONSTRAINT PK_test PRIMARY KEY (a)



 

mysql为已经建立的表设置其主键(primary key)

标签: mysql数据库编程语言
 分类:
数据库mysql
Database changed
mysql> desc orders;
+-------------+-------------+------+-----+---------+-------+
| Field                    | Type                | Null           | Key   | Default     | Extra |
+-------------+-------------+------+-----+---------+-------+
| Company           | varchar(20)    | YES          |            | NULL      |            |
| OrderNumber    | int(5)               | YES          |            | NULL      |            |
| Id_O                    | int(4)               |          NO   |            | 1              |             |

+-------------+-------------+------+-----+---------+-------+

建立的orders如上,现在想设置Id_O为primary key

应该先将其删除

MySQL > alter table orders drop Id_O;

在填曾:

mysql> alter table Orders add Id_O int not null primary key Auto_increment; ;

需要设置其为自增型,否则,因为空缺等问题而不能设置Id_O为主键;

mysql> select * from orders;
+----------       +-------------       +----+
| Company    | OrderNumber | Id |
+----------       +-----------       --+----+
| IBM               |        3532 |  1   |
| W3School   |        2356 |  2   |
| Apple           |        4698 |  3   |
| W3School   |        6953 |  4   |
+----------       +-------------        +----+

 

改变primary key为自增型:

 alter table tb_name modify id int auto_increment.










Mysql设置自增长主键的初始值

 分类:
web-php(5)   web-javascript(4) 

alter table table_name auto_increment=n;
注意n只能大于已有的auto_increment的整数值,小于的值无效.
show table status like 'table_name' 可以看到auto_increment这一列是表现有的值.
步进值没法改变.只能通过下面提到last_inset_id()函数变通使用

MySQL可以使用AUTO_INCREMENT来设定主键的值为自增长的,其默认值是1,如果想把它的初始值设置为1000,比较笨的办法是先插入一条记录并指定主键的值为999,然后delete改行记录,例如:

 

[sql]  view plain  copy
 
  1. insert into test(pk) values(999);   
  2. delete from test where pk = 999;  

 


更好的方法是使用alter的方法来直接修改,例如:

 

[sql]  view plain  copy
 
  1. alter table test AUTO_INCREMENT = 1000;  

 


例子

1、不控制主键的起点

 

[sql]  view plain  copy
 
  1. create table emb_t_dictBusType  
  2. (  
  3.    emb_c_busTypeID      int not null auto_increment,  
  4.    emb_c_busTypeEnName  varchar(255) not null,  
  5.    emb_c_busTypeZhName  varchar(255) not null,  
  6.    primary key(emb_c_busTypeID)    
  7. )engine=INNODB  default charset=gbk;  
[sql]  view plain  copy
 
  1. <span style="font-family: Simsun; background-color: rgb(255, 255, 255);">2、控制主键的起点</span>  
[sql]  view plain  copy
 
  1. <span style="font-family: Simsun; background-color: rgb(255, 255, 255);"></span><pre name="code" class="sql">create table emb_t_dictBusType  
  2. (  
  3.    emb_c_busTypeID      int not null auto_increment,  
  4.    emb_c_busTypeEnName  varchar(255) not null,  
  5.    emb_c_busTypeZhName  varchar(255) not null,  
  6.    primary key(emb_c_busTypeID)    
  7. )engine=INNODB auto_increment=1001 default charset=gbk;  


自增主键归零

 

 
     

 

方法一:


如果曾经的数据都不需要的话,可以直接清空所有数据,并将自增字段恢复从1开始计数 
truncate table 表名

方法二:


dbcc checkident (’table_name’, reseed, new_reseed_value) 当前值设置为 new_reseed_value。如果自创建表后没有将行插入该表,则在执行 DBCC CHECKIDENT 后插入的第一行将使用 new_reseed_value 作为标识。否则,下一个插入的行将使用 new_reseed_value + 1。如果 new_reseed_value 的值小于标识列中的最大值,以后引用该表时将产生 2627 号错误信息。 www.111cn.net
方法二不会清空已有数据,操作比较灵活,不仅可以将自增值归零,也适用于删除大量连续行后,重新设置自增值并插入新的数据;或从新的值开始,当然不能和已有的冲突。

 

[sql]  view plain  copy
 
  1. $sql="delete from $table_vote";   
  2. mysql_query($sql, $link);   
  3. $sql="alter table $table_vote auto_increment=1";   
  4. mysql_query($sql, $link);  


通常我们在应用中对mysql执行了insert操作后,需要获取插入记录的自增主键。本文将介绍java环境下的4种方法获取insert后的记录主键auto_increment的值:
获取自增主键【4种方法】

 

通过JDBC2.0提供的insertRow()方式
通过JDBC3.0提供的getGeneratedKeys()方式
通过SQL select LAST_INSERT_ID()函数
通过SQL @@IDENTITY 变量


1. 通过JDBC2.0提供的insertRow()方式
自jdbc2.0以来,可以通过下面的方式执行。

 

[sql]  view plain  copy
 
  1. Statement stmt = null;  
  2. ResultSet rs = null;  
  3. try {  
  4.     stmt = conn.createStatement(java.sql.ResultSet.TYPE_FORWARD_ONLY,  // 创建Statement  
  5.                                 java.sql.ResultSet.CONCUR_UPDATABLE);  
  6.     stmt.executeUpdate("DROP TABLE IF EXISTS autoIncTutorial");  
  7.     stmt.executeUpdate(                                                // 创建demo表  
  8.             "CREATE TABLE autoIncTutorial ("  
  9.             + "priKey INT NOT NULL AUTO_INCREMENT, "  
  10.             + "dataField VARCHAR(64), PRIMARY KEY (priKey))");  
  11.     rs = stmt.executeQuery("SELECT priKey, dataField "                 // 检索数据  
  12.        + "FROM autoIncTutorial");  
  13.     rs.moveToInsertRow();                                              // 移动游标到待插入行(未创建的伪记录)  
  14.     rs.updateString("dataField", "AUTO INCREMENT here?");              // 修改内容  
  15.     rs.insertRow();                                                    // 插入记录  
  16.     rs.last();                                                         // 移动游标到最后一行  
  17.     int autoIncKeyFromRS = rs.getInt("priKey");                        // 获取刚插入记录的主键preKey  
  18.     rs.close();  
  19.     rs = null;  
  20.     System.out.println("Key returned for inserted row: "  
  21.         + autoIncKeyFromRS);  
  22. }  finally {  
  23.     // rs,stmt的close()清理  
  24. }  

 


2. 通过JDBC3.0提供的getGeneratedKeys()方式

 

[sql]  view plain  copy
 
  1. Statement stmt = null;  
  2. ResultSet rs = null;  
  3. try {  
  4.     stmt = conn.createStatement(java.sql.ResultSet.TYPE_FORWARD_ONLY,  
  5.                                 java.sql.ResultSet.CONCUR_UPDATABLE);    
  6.     // ...  
  7.     // 省略若干行(如上例般创建demo表)  
  8.     // ... www.111cn.net  
  9.     stmt.executeUpdate(  
  10.             "INSERT INTO autoIncTutorial (dataField) "  
  11.             + "values ('Can I Get the Auto Increment Field?')",  
  12.             Statement.RETURN_GENERATED_KEYS);                      // 向驱动指明需要自动获取generatedKeys!  
  13.     int autoIncKeyFromApi = -1;  
  14.     rs = stmt.getGeneratedKeys();                                  // 获取自增主键!  
  15.     if (rs.next()) {  
  16.         autoIncKeyFromApi = rs.getInt(1);  
  17.     }  else {  
  18.         // throw an exception from here  
  19.     }   
  20.     rs.close();  
  21.     rs = null;  
  22.     System.out.println("Key returned from getGeneratedKeys():"  
  23.         + autoIncKeyFromApi);  
  24. }  finally { ... }  
[sql]  view plain  copy
 
  1. <span style="font-weight: bold; font-family: Simsun; background-color: rgb(255, 255, 255);">使用AUTO_INCREMENT时,应注意以下几点:</span>  

 

AUTO_INCREMENT是数据列的一种属性,只适用于整数类型数据列。

设置AUTO_INCREMENT属性的数据列应该是一个正数序列,所以应该把该数据列声明为UNSIGNED,这样序列的编号个可增加一倍。

AUTO_INCREMENT数据列必须有唯一索引,以避免序号重复。

AUTO_INCREMENT数据列必须具备NOT NULL属性。

AUTO_INCREMENT数据列序号的最大值受该列的数据类型约束,如TINYINT数据列的最大编号是127,如加上UNSIGNED,则最大为255。一旦达到上限,AUTO_INCREMENT就会失效。

  • 2
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值