mysql 创建单表外键关联多表

创建students表关联country,position,gender三张表

 create table country(
 cid int primary key auto_increment,
 cname varchar(10) NOT NULL
)ENGINE=INNODB DEFAULT CHARSET=utf8;
 
 create table `position`(
 pid int primary key auto_increment,
 pname varchar(10) NOT NULL
)ENGINE=INNODB DEFAULT CHARSET=utf8;

create table Gender(
 gid int primary key auto_increment,
 gname varchar(10) NOT NULL
)ENGINE=INNODB DEFAULT CHARSET=utf8;

create table students(
 sid int primary key auto_increment,
 sname varchar(100) not null,
 countryId int,
 positionId int,
 GenderId int,
 Capability int,
 constraint fk_stu_cid foreign key(countryId)
 references country(cid),
 constraint fk_stu_pid foreign key(positionId)
 references `position`(pid),
 constraint fk_stu_gid foreign key(GenderId)
 references Gender(gid)
 )ENGINE=INNODB DEFAULT CHARSET=utf8;  

insert into students(sname,countryId,positionId,GenderId,Capability) values('刘备',3,2,1,80);
insert into students(sname,countryId,positionId,GenderId,Capability) values('曹操',1,1,1,76);

id    name countryId positionId GenderId Capability
刘备   蜀       打野	   男         80
曹操   魏        top     男         76
孙策
孙尚香  吴        AD    女         88
诸葛亮  蜀       ap     男        87
周瑜
黄忠
关羽
张飞
赵云
小乔
大乔
貂蝉
吕布
夏侯惇

insert into country(cname) values('魏');

id  country
1    魏
2    蜀
3    吴

insert into `position`(pname) values('top');
insert into `position`(pname) values('jungle');
insert into `position`(pname) values('ap');
insert into `position`(pname) values('ad');
insert into `position`(pname) values('sup');
id  position
1   top
2   jungle
3   ap
4   ad
5   sup

insert into Gender(gname) values('男');
insert into Gender(gname) values('女');
id   Gender
1    female
2    male

查询

select * from students s,country c,position p,Gender g where s.countryId = c.cid and s.positionId = p.pid and s.GenderId = g.gid;

发布了189 篇原创文章 · 获赞 86 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/seulzz/article/details/103716815
今日推荐