外键
语法: Alter table 表名 add constraint 外键名称 foreign key (外键字段名) references 主表(主表列名)
语法二: 如果是在建表时添加的外键,则可以舍去alter table 表名 add 然后从constraint开始书写
删除语法:alter table 表名 drop foreign key 外键名称
我们执行删除语法后,两个表的连接就消失了
通常外键字段名和主表列名就是相互连接的两个字段
外键名称自定义
表名通常为列数较多的表的表名
-- 外键
create table dept(
id int auto_increment comment'ID' primary key ,
name varchar(20) not null comment'部门名称'
)comment'部门表';
insert into dept(id,name)values(1,'研发部'),(2,'市场部');
create table emp (
id int auto_increment comment'ID' primary key ,
name varchar(50) not null comment '姓名',
age int comment '年龄',
newid int comment '部门ID'
)comment'员工表';
insert into emp(id,name,age,newid) values
(1,'sdas',66,1),
(23,'sdasdasdsaw',56,2),
(14,'sdadaws',86,1);
alter table emp add constraint wkeyname foreign key (newid) references dept(id);
select * from emp;
select * from dept;
-- 删除外键
alter table emp drop foreign key wkeyname;
如图所示,两张表格已经连接起来
第一张图的newid的左侧有蓝色小钥匙,这就表明此表的newid已经与第二张图的id这个主键连接了
当我们执行外键删除语句的时候,则蓝色的小钥匙就会消失,此时二者的连接将失去,在这时,如果我们将表二的字段删除,不会报错,也不会对表一产生任何影响
对于外键: 我们通常是多对一的关系,我们需要在表的内容多的那个表中去创建外键然后与一所对的表的主键进行一个绑定,外键一旦添加,则表内的数据将无法删除,可以保证数据的一致性和完整性,让两张表的数据之间建立联系