mysql创建class表_<MySQL>MySQL创建表及相关约束

本文介绍了如何在MySQL中创建多个表,包括class表、student表、teacher表、course表和score表,并通过外键约束建立它们之间的联系。详细展示了每个表的创建语句,以及数据的插入过程,特别提到了外键约束的使用和避免名称冲突的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

第一个表创建:

create table class(

cid int not null auto_increment primary key,

caption char(20) not null

)engine=innodb default charset=utf8;

插入数据:

insert into class(caption) values('三年二班');

insert into class(caption) values('一年三班');

insert into class(caption) values('三年一班');

9d11dfab0bdb42e703937c642073053c.png

第二个表创建:

create table student(

sid int not null auto_increment primary key,

sname char(20) not null,

gender char(20) not null,

class_id int

)engine=innodb default charset=utf8;

增加约束(外键):

alter table student add constraint foreign key student(class_id) references class(cid);

插入数据:

insert student(sname,gender,class_id) values('钢弹','女',1);

insert student(sname,gender,class_id) values('铁锤','女',1);

insert student(sname,gender,class_id) values('山炮','男',2);

bc46a4fd6151a2f5a8cc2b9b104aca13.png

第三个表创建:

create table teacher(

tid int not null auto_increment primary key,

tname char(20) not null

)engine=innodb default charset=utf8;

插入数据:

insert teacher(tname) values('波多');

insert teacher(tname) values('苍空');

insert teacher(tname) values('饭岛');

d4e017b18764127ad838c998a5d533f1.png

第四个表创建:

create table course(

cid int not null auto_increment primary key,

cname char(20) not null,

tearch_id int

)engine=innodb default charset=utf8;

增加约束:

alter table course add constraint foreign key course(tearch_id) references teacher(tid);

插入数据:

insert course(cname,tearch_id) values('生物',1);

insert course(cname,tearch_id) values('体育',1);

insert course(cname,tearch_id) values('物理',2);

98e01e4864328acc865a3e38e8a43bc5.png

第五个表创建:

create table score(

sid int not null auto_increment primary key,

student_id int not null,

corse_id int not null,

number int not null

)engine=innodb default charset=utf8;

增加约束:

alter table score add constraint foreign key score(student_id) references student(sid);

alter table score add constraint foreign key (corse_id) references course(cid);

可能存在的问题:

假设第二句写成:alter table score add constraint foreign key score(corse_id) references course(cid);

会报错:ERROR 1061 (42000): Duplicate key name 'score'

原因是:外键名称重复,在key后面增加表名会默认作为外键名,因此如果写2条,就会出现外键名称重复

解决办法:删除key后面的表名,mysql会默认增加索引

插入数据:

insert score(student_id,corse_id,number) values(1,1,60);

insert score(student_id,corse_id,number) values(1,2,59);

insert score(student_id,corse_id,number) values(2,2,100);

a4106459f748da31863197e1ea423da6.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值