码迷,mamicode.com
首页 > 其他好文 > 详细

连表操作

时间:2017-04-18 00:36:49      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:join   rom   操作   关系   image   png   creat   主键   类型   

 

连表

 

多表关联,一对多的关系。

将一张表分成两张表。

  • 人为创建关联
  • 约束

外键是另外一张表的主键。主表的栏位、与参考表栏位,对应类型相同。

 

一张表分成两张表(因为partment部分是重复的)

技术分享

 

技术分享

 

 

 

create table part(
nid int not null  auto_increment  primary key,
caption varchar(32) not null
);

create table person(
nid int not null auto_increment,
name varchar(32) not null,
email varchar(32) not null,
part_nid int not null,
primary key (nid),
constraint fk_person_part foreign key (part_nid) references part(nid)
);

技术分享

技术分享

技术分享

 

alter table person drop foreign key fk_person_part; #删除外键
alter table person add constraint fk_per_t1 foreign key (part_nid) references part(nid);  #添加外键

 

#找到CEO部门的所有人员姓名

select
    person.name,
    part.caption
from
    person
left join part on person.part_nid = part.nid
where
    part.caption = CEO

技术分享

 

 

A left join B on a.xx = b.xx
#以A为主
#将A中所有数据罗列
#B,则只显示与A相应的数据

B left join A

A right join B  == B left join A

A inner join B
#自动忽略未建立关系的数据。

 

 技术分享

 

技术分享

 

 技术分享

 

 

建立三张表

 

技术分享

 

 技术分享

 

连表操作

标签:join   rom   操作   关系   image   png   creat   主键   类型   

原文地址:http://www.cnblogs.com/ttrrpp/p/6725770.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!