主键(primary key)和唯一键(unique) 知识点总
2019-01-18 本文已影响0人
超级皮波9
Primary key
-
概念
主键用于唯一标识表中的每一条数据 -
主键的特征:
不能重复, 不能为空
示例
create table if not exists stu(
id int auto_increment primary key, <------#主建
name varchar(20)
);
注意点:
auto_increment的字段必须是主键, 但是主键不一定是auto_increment的, 只要是唯一的就可以 一个表只能有一个主键, 但是主键可以是1个或多个字段组成
auto_increment 自增长
1. 自增长字段的值从1开始, 每次递增1
2. 自增长字段数据不可以重复, 合适生成唯一的id
3. 自增长字段可以使用null或者default来设置值
4. 自增长字段必须是主键 (primary key)
示例演示
示例1
# 错误示例
create table if not exists stu2(
id int auto_increment, <------#会报错, 自增长的字段必须是主键
name varchar(20)
);
示例2
create table if not exists stu2(
id int primary key, <------#不会报错, 主键不一定是自增长的
name varchar(20)
);
#如果主键不是自增长的, 那么不能为空
#主键不能重复
示例3
# 错误示例
create table if not exists stu3(
id1 int primary key,
id2 int primary key, <------#一张表只能有一个主键
name varchar(20)
);
#正确的写法
create table if not exists stu3(
id1 int primary key,
id2 int,
name varchar(20)
);
示例4
#指定主键的第二种格式
create table if not exists stu4(
id1 int,
id2 int,
name varchar(20),
primary key(id1)
);
示例5
create table if not exists stu6(
id int,
name varchar(20)
);
# 没有主键的情况下添加主建
alter table stu6 add primary key(id);
示例6
# 联合主建
create table if not exists stu5(
id1 int,
id2 int,
name varchar(20),
primary key(id1,id2)
);
#不是指定两个主键, 一个primary key就是指定一个主键
#这里只出现了一个primary key, 所以只指定了一个主键
#只不过这个主键比较特殊, 是由两个字段共同组成的
联合主键的应用场景:
- 如下一张表无论哪一个字段都无法保证数据的唯一性,
- 所以可以使用多个字段组合再一起保证数据的唯一性
企业开发中如何选择主键?
- 最少性: 尽量选择一个字段作为主键
- 稳定性: 尽量选择更新少的字段作为主键
- 尽量选择整数类型的字段作为主键
- 结论: 搞一个id字段类型为int, 设置自动增长, 作为主键
唯一键unique
作用
避免添加重复数据, 也就是说如果想保证某一个字段的值永远不重复, 那么就可以将这个字段设置为唯一键
注意点:
- 唯一键不是主键, 主键有一个特点是不能重复, 但是唯一键不等于主键
- 一张表中只能有一个主键, 但是一张表中可以有多个唯一键
示例1
create table if not exists stu1(
id int auto_increment primary key,
name varchar(20) <------ #可以添加重复数据
);
create table if not exists stu2(
id int auto_increment primary key,
name varchar(20) unique <------#不可以添加重复数据
);
#添加唯一键的第二种方式
create table if not exists stu(
id int auto_increment primary key,
name varchar(20),
unique key(name) <------#给name添加唯一键 name不可以添加重复数据
);
示例3
create table if not exists stu(
id int auto_increment primary key,
name varchar(20)
);
alter table stu add unique(name); <------#指定唯一键
示例4
# 指定多个唯一键
create table if not exists stu11(
id int auto_increment primary key,
name varchar(20) unique,
score int unique
);
删除唯一键
格式
alter table 表名 drop index 唯一键字段名;
示例
alter table stu11 drop index name;