Mysql系列课程--第二章 约束 自增主键

一.约束(保证数据的合理性)
1.not Null 非空约束,不能为null
2.unique 唯一约束 , 不能重复
3.primary key 主键约束 ,唯一标识这条数据
4.foreign key 外键约束,用来连接两张表,这张表的外键一定是另一张表的主键
5.check 检查约束,判断数据是否合理
6.default 默认约束 ,如果你不设置,则插入默认值

二. unique 唯一约束 与 primary key 主键约束 的区别
1.一张表里只能有一个主键,可以有多个唯一约束
2.唯一约束可以为空(除SQL SERVER外均可出现多个null值),主键不可以

三.添加约束
1.为teahcer添加tno为主键

alter table teacher add column tno int primary key;

2.添加一个唯一约束

 alter table teacher add constraint uk_name unique(name);

3.删除唯一约束

alter table teacher drop index uk_name;

4.删除主键

alter table teacher drop primary key;

5.新增一个主键

alter table teacher add constraint pk_tno primary key(tno);

6.添加外键

 alter table student add constraint fk_tno foreign key(tno) references teacher(tno);

四.自增主键

create table student(
    s_no int primary key auto_increment,
    s_name varchar(20),
    s_sex varchar(5),
    s_age int
)

添加一条信息(表名后面一定要加插入的相应字段)

insert student(s_name,s_sex,s_age) values('李文辉','女',20);

详细课程查询:
Mysql系列课程–第一章 Sql分类 常用命令
Mysql系列课程–第二章 约束 自增主键
Mysql系列课程–第三章 建表 插数据
Mysql系列课程–第四章 备份 普通查询
Mysql系列课程–第五章 高级查询 表连接 子查询 case when
Mysql系列课程–第六章 索引和视图
Mysql系列课程–第七章 触发器和存储过程
Mysql系列课程–第八章 sql精选35道题

猜你喜欢

转载自blog.csdn.net/u012843355/article/details/78632939