自动增长(auto_increment) 字段值从1开始,每次递增1,自动增长的值就不会有重复,适合用来生成唯一的id。在MySQL中只要是自动增长列必须是主键 主键(primary key)主键概念:唯一标识表中的记录的一个或一组列称为主键。 特点: - 1、不能重复、不能为空
- 2、一个表只能有一个主键。
复制代码 作用:- 最少性:尽量选择单个键作为主键
- 稳定性:尽量选择数值更新少的列作为主键
- 比如:学号,姓名、地址 这三个字段都不重复,选哪个做主键
- 选学号,因为学号最稳定
复制代码- -- 创建主键方法一
- mysql> create table stu20(
- -> id int auto_increment primary key,
- -> name varchar(20)
- -> );
- Query OK, 0 rows affected (0.04 sec)
- -- 创建主键方法二
- mysql> create table stu21(
- -> id int auto_increment,
- -> name varchar(20),
- -> primary key(id)
- -> );
- Query OK, 0 rows affected (0.02 sec)
复制代码 组合键- mysql> create table stu22(
- -> classname varchar(20),
- -> stuname varchar(20),
- -> primary key(classname,stuname) -- 创建组合键
- -> );
- Query OK, 0 rows affected (0.00 sec)
- mysql> desc stu22;
- +-----------+-------------+------+-----+---------+-------+
- | Field | Type | Null | Key | Default | Extra |
- +-----------+-------------+------+-----+---------+-------+
- | classname | varchar(20) | NO | PRI | | |
- | stuname | varchar(20) | NO | PRI | | |
- +-----------+-------------+------+-----+---------+-------+
- 2 rows in set (0.00 sec)
复制代码 通过更改表添加主键- mysql> create table stu23(
- -> id int,
- -> name varchar(20)
- -> );
- Query OK, 0 rows affected (0.05 sec)
- -- 添加主键
- mysql> alter table stu23 add primary key(id);
- Query OK, 0 rows affected (0.09 sec)
- Records: 0 Duplicates: 0 Warnings: 0
复制代码 删除主键- mysql> alter table stu23 drop primary key;
- Query OK, 0 rows affected (0.03 sec)
- Records: 0 Duplicates: 0 Warnings: 0
复制代码 插入数据- mysql> create table stu25(
- -> id tinyint unsigned auto_increment primary key,
- -> name varchar(20)
- -> );
- Query OK, 0 rows affected (0.05 sec)
- -- 插入数据
- mysql> insert into stu25 values (3,'tom'); -- 可以直接插入数字
- Query OK, 1 row affected (0.06 sec)
- -- 自动增长列可以插入null,让列的值自动递增
- mysql> insert into stu25 values (null,'berry');
- Query OK, 1 row affected (0.00 sec)
复制代码小结: 1、只要是auto_increment必须是主键,但是主键不一定是auto_increment 2、主键特点是不能重复不能为空 3、一个表只能有一个主键,但是一个主键可以有多个字段组成 4、自动增长列通过插入null值让其递增 5、自动增长列的数据被删除,默认不再重复使用。truncate table删除数据后,再次插入从1开始 |