mysql数据库操作之自动增长(auto_increment)和主键

[复制链接]
查看1972 | 回复0 | 2020-9-29 11:34 | 显示全部楼层 |阅读模式
自动增长(auto_increment)
字段值从1开始,每次递增1,自动增长的值就不会有重复,适合用来生成唯一的id。在MySQL中只要是自动增长列必须是主键
主键(primary key)
主键概念:唯一标识表中的记录的一个或一组列称为主键。
特点:
  1. 1、不能重复、不能为空
  2. 2、一个表只能有一个主键。
复制代码
作用:
  1. 1、保证数据完整性
  2. 2、加快查询速度
复制代码
选择主键的原则
  1. 最少性:尽量选择单个键作为主键
  2. 稳定性:尽量选择数值更新少的列作为主键

  3. 比如:学号,姓名、地址  这三个字段都不重复,选哪个做主键
  4. 选学号,因为学号最稳定
复制代码
  1. -- 创建主键方法一
  2. mysql> create table stu20(
  3.     -> id int auto_increment primary key,
  4.     -> name varchar(20)
  5.     -> );
  6. Query OK, 0 rows affected (0.04 sec)

  7. -- 创建主键方法二
  8. mysql> create table stu21(
  9.     -> id int auto_increment,
  10.     -> name varchar(20),
  11.     -> primary key(id)
  12.     -> );
  13. Query OK, 0 rows affected (0.02 sec)
复制代码
组合键
  1. mysql> create table stu22(
  2.     -> classname varchar(20),
  3.     -> stuname varchar(20),
  4.     -> primary key(classname,stuname)  -- 创建组合键
  5.     -> );
  6. Query OK, 0 rows affected (0.00 sec)

  7. mysql> desc stu22;
  8. +-----------+-------------+------+-----+---------+-------+
  9. | Field     | Type        | Null | Key | Default | Extra |
  10. +-----------+-------------+------+-----+---------+-------+
  11. | classname | varchar(20) | NO   | PRI |         |       |
  12. | stuname   | varchar(20) | NO   | PRI |         |       |
  13. +-----------+-------------+------+-----+---------+-------+
  14. 2 rows in set (0.00 sec)
复制代码
通过更改表添加主键
  1. mysql> create table stu23(
  2.     -> id int,
  3.     -> name varchar(20)
  4.     -> );
  5. Query OK, 0 rows affected (0.05 sec)

  6. -- 添加主键
  7. mysql> alter table stu23 add primary key(id);
  8. Query OK, 0 rows affected (0.09 sec)
  9. Records: 0  Duplicates: 0  Warnings: 0
复制代码
删除主键
  1. mysql> alter table stu23 drop primary key;
  2. Query OK, 0 rows affected (0.03 sec)
  3. Records: 0  Duplicates: 0  Warnings: 0
复制代码
插入数据
  1. mysql> create table stu25(
  2.     -> id tinyint unsigned auto_increment primary key,
  3.     -> name varchar(20)
  4.     -> );
  5. Query OK, 0 rows affected (0.05 sec)

  6. -- 插入数据
  7. mysql> insert into stu25 values (3,'tom');   -- 可以直接插入数字
  8. Query OK, 1 row affected (0.06 sec)

  9. -- 自动增长列可以插入null,让列的值自动递增
  10. mysql> insert into stu25 values (null,'berry');
  11. Query OK, 1 row affected (0.00 sec)
复制代码
小结:
1、只要是auto_increment必须是主键,但是主键不一定是auto_increment
2、主键特点是不能重复不能为空
3、一个表只能有一个主键,但是一个主键可以有多个字段组成
4、自动增长列通过插入null值让其递增
5、自动增长列的数据被删除,默认不再重复使用。truncate table删除数据后,再次插入从1开始
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

UID
1
贡献
387
丢币
38902
主题
4607
回帖
116
注册时间
2018-9-25
最后登录
2024-4-16