一、创建主表
create table if not EXISTS staff(
staff_id INT PRIMARY key,
department varchar (50)
);
INSERT into staff values(1,'software');
INSERT into staff values(2,'hr');
INSERT into staff values(5,'electric');
主表中的主键是staff_id ;
二、创建子表
create table if not EXISTS staff_info(
identify_id int primary key,
id int null ,
staff_name varchar(50),
foreign key(id) REFERENCES staff(staff_id)
);
insert into staff_info values(12345,1,'lilei');
insert into staff_info values(14578,2,'wangmin');
insert into staff_info(identify_id,staff_name) values(14324,'xiaochen');--子表中外键所在的列可以为空,但是主键列不能为空
insert into staff_info values(14689,3,‘chenxiao’);–子表中外键列的值必须在主表中列存在
DELETE from staff where staff_id=1;--无法删除主表中已经被子表引用的行
DELETE from staff where staff_id=5;--可以删除主表中没有被子表引用的行
1)子表staff_info中的外键是id这列,该外键和主表staff中的主键staff_id 相关联;
2)外键id中的值可以为空;
3)外键id中的非空值必须是主表中主键staff_id 中的某个值,这里可以发现id等于3时会提示数据插入错误;
4)删除主表中的id时,如果该id的值没有被子表引用就可以删除,比如id=5的行可以删除;
5)删除主表中的id时,如果该id的值被子表引用就不能删除;
6)更新主表中非主键列是被允许的,例如:
UPDATE staff set department='it' where department='hr';