当前位置:Gxlcms > 数据库问题 > mysql 的完整性约束 与单表查询

mysql 的完整性约束 与单表查询

时间:2021-07-01 10:21:17 帮助过:6人阅读

1 foreign key 外键 建立两张表的联系

1 创建表时先创建被关联的表 在创建关联表
create table dep(
   id int primary key,
   name varchar(20) not null,
  descripe varchar(20) not null);



在创建关联表(emp表)

create table emp(
  id int primary key,
 name varchar(20) not null,
 age int not null,
 dep_id int,
 cinstraint fk_dep foregin key(dep_id) references dep(id));


2 插入记录时 先往被关联表中插入记录 再往关联表中插入记录

insert into dep values
(1,‘IT‘,‘IT技术有限部门‘),
(2,‘销售部‘,‘销售部门‘),
(3,‘财务部‘,‘花钱太多部门‘);


insert into emp values
(1,‘zhangsan‘,18,1),
(2,‘lisi‘,19,1),
(3,‘egon‘,20,2);


在关联表中加入 
on delete cascade  #同步删除
on update cascade #同步更新


修改emp 表
create table emp(
id int primary key,
name varchar(20) not null,
age int not null,
dep_id int,
constraint fk_dep foregin key(dep_id) references dep(id)
on delete cascade
on update cascade);

 

mysql 的完整性约束 与单表查询

标签:同步   pre   修改   cascade   name   联系   部门   enc   desc   

人气教程排行