06-主键和唯一键

2019-01-08  本文已影响0人  亨锅锅

1.auto_increment 自增长
1.1自增长字段的值从1开始, 每次递增1
1.2自增长字段数据不可以重复, 合适生成唯一的id
1.3自增长字段可以使用null或者default来设置值
1.4自增长字段必须是主键 (primary key)

create table if not exists stu(
id int auto_increment primary key,
name varchar(20)
);
insert into stu values(null, 'lnj');
insert into stu values(default, 'zq');

2.主键(primary key)
主键用于唯一标识表中的每一条数据, 和现实生活中的身份证很像
1 'zs' 33
2 'zs' 33
主键的特征:

示例一:
create table if not exists stu2(
id int auto_increment, #会报错, 自增长的字段必须是主键
name varchar(20)
);

create table if not exists stu2(
id int primary key, #不会报错, 主键不一定是自增长的
name varchar(20)
);
insert into stu2 values(null, 'lnj'); #如果主键不是自增长的, 那么不能为空
insert into stu2 values(1, 'lnj');
insert into stu2 values(1, 'zq'); #主键不能重复

示例二:
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)
);
create table if not exists stu4(
id1 int,
id2 int,
name varchar(20),
primary key(id1) #指定主键的第二种格式
);

create table if not exists stu5(
id1 int,
id2 int,
name varchar(20),
#不是指定两个主键, 一个primary key就是指定一个主键
#这里只出现了一个primary key, 所以只指定了一个主键
#只不过这个主键比较特殊, 是由两个字段共同组成的
primary key(id1,id2)
);

联合主键的应用场景:
如下一张表无论哪一个字段都无法保证数据的唯一性,
所以可以使用多个字段组合再一起保证数据的唯一性
id height name
1 1.75 lnj
1 1.62 lnj
2 1.75 ww

示例三:
create table if not exists stu6(
id int,
name varchar(20)
);
alter table stu6 add primary key(id);


3.唯一键
unique: 唯一键
unique作用:
避免添加重复数据, 也就是说如果想保证某一个字段的值永远不重复, 那么就可以将这个字段设置为唯一键
unique注意点:

示例一:
create table if not exists stu7(
id int auto_increment primary key,
name varchar(20) #可以添加重复数据
);
insert into stu7 values(null, 'lnj');
insert into stu7 values(null, 'lnj');

create table if not exists stu8(
id int auto_increment primary key,
name varchar(20) unique #不可以添加重复数据
);
insert into stu8 values(null, 'lnj');
insert into stu8 values(null, 'lnj');

示例二:
create table if not exists stu9(
id int auto_increment primary key,
name varchar(20),
unique key(name) #不可以添加重复数据
);
insert into stu9 values(null, 'lnj');
insert into stu9 values(null, 'lnj');

示例三:
create table if not exists stu10(
id int auto_increment primary key,
name varchar(20)
);
alter table stu10 add unique(name); #指定唯一键

示例四:
create table if not exists stu11(
id int auto_increment primary key,
name varchar(20) unique,
score int unique
);
insert into stu11 values(null, 'lnj', 99);
insert into stu11 values(null, 'lnj', 100);

示例五:
alter table 表名 drop index 唯一键名;
alter table stu11 drop index name; #删除唯一键

上一篇 下一篇

猜你喜欢

热点阅读