python学习笔记 day44 外键约束

1. 外键约束

约束是一种限制,它通过对表的行或列的数据做出限制,来确保表数据的完整性和唯一性;

一张表的主键在其它表中就成为外键;(比如之前dept表的id 是主键,另一张person表的dept_id与之对应就是外键)

场景:

person表人员信息其实是不能没有dept_id 部门id的,所以在创建表时需要对表的dept_id做一个约束,简单来说就是对两个表的关系进行一些约束,即foreign key

foreign key: 表与表之间的某种约束关系,由于这种关系的存在能够让表与表之间的数据更加完整,关联性更强;

1.1 在创建表时就对表的某些字段(与另一张表的主键相关联的字段)进行外键约束设置;

table person2(
  id int not null auto_increment primary key,
  name varvhar(50) not null,
  age int not NULL,
  sex char(2) not null,
  salary int not null,
  dept_id int not NULL
  constraint fk_did foreign key(dept_id) references dept(did))   # 为person表的dept_id设置外键

1.2 已经创建表后追加外键约束:

外键关联的那张表,,dept表的did必须设置为主键,person表的dept_id才可以设置为外键

alter table dept add primary key(did)  # dept表的did必须得设为主键,才能为person表的dept_id设为外键
alter table person add constraint fk_did foreign key(dept_id) references dept(did);


一般外键是不可以为空的!!!

删除主键:alter table person drop foreign key fk_did;

alter table person drop foreign key fk_did;  # 删除外键
desc person;
alter table person modify dept_id int not null;  # 外键不能为空
alter table person add constraint fk_did foreign key(dept_id) references dept(did);

运行结果:

 

 

定义外键的条件:

1. 外键字段对应的字段数据类型需要保持一致,且被关联的字段(references 指定的另一张表的字段did 必须唯一dept(did)) ;

2. 所有tables的存储引擎必须为INNODB类型的;

3. 外键的约束有四种类型,1 RESTRICT (主表 dept表不能随便删除,因为从表person中设置为外键的字段dept_id需要用到dept中主键did字段的值)2.NO ACTION 3. CASCADE(主表删了,从表对应的数据也就没了,这个慎用!!!)      4. SET NULL;

4. 建议: 如果需要外键约束,最好创建表同时创建外键约束;

                如果需要设置级联关系,删除时最好设置为set null

 注意: 插入数据之前,先插入主表(dept)中数据,再插入从表(person)中的数据;

             删除数据时,先删除从表(person)中的数据,再删除主表中的数据;

2. 其他约束类型

2.1 非空约束 NOT NULL  非空,用来约束表中的字段列;

2.2 主键约束:用来约束表中一行,作为一行的标识符,在一张表中通过主键就可以精准定位到某一行;(主键这一行的数据不能重复且不能为空)

create table info(
 id int not null,
  name varchar(50) not null,
  primary key(id,name))  # 设置为联合主键

2.3 唯一约束: 关键字UNIQUE 规定表中指定的一列值必须不能重复,即这一列的值都唯一(UNIQUE可以设置多个,也可以某两个字段一起设置为UNIQUE 也就是两个字段不都一样就可以,跟主键的区别是,主键无论是单一字段设置为主键还是联合主键都必须有一个,而唯一约束是可以设置多个)

create table info2(
  id int not null,
  name varchar(30) not null,
  age int not null,
  salary int not NULL,
  Unique id_name(id,name)
  )

运行结果(往info2中插入数据时,id,name的值在两条数据中不能同时一样)

 4. 默认值约束 default

create table info3(
  id int not null,
  name varchar(20) not null default "张三")

insert into info3(id,name) values(1,default),(2,default)
insert into info3(id) values(3),(4)
select * from info3;

运行结果:

 

猜你喜欢

转载自www.cnblogs.com/xuanxuanlove/p/9886198.html