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);

更多相关文章

  1. Mysql_案例1:查询出每个部门工资最高的员工信息
  2. sql grouping with rollup 按部门 合并一些部门

随机推荐

  1. Android与HTML JavaScript交互
  2. Android 游戏开发的一些基础和经验
  3. android sqlite 介绍
  4. Android模拟器
  5. Android如何使布局中图(ImageButton)和文字
  6. Android实现2D翻转动画
  7. Android开发入门
  8. Android(安卓)WebView 开发详解(二)
  9. 【博客园客户端】博客园Android客户端更
  10. Android UI主线程与子线程