mysql创建表格1warning_MySQLMySQL创建表及相关约束
第一個表創(chuàng)建:
create table class(
cid int not null auto_increment primary key,
caption char(20) not null
)engine=innodb default charset=utf8;
插入數(shù)據(jù):
insert into class(caption) values('三年二班');
insert into class(caption) values('一年三班');
insert into class(caption) values('三年一班');
第二個表創(chuàng)建:
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);
插入數(shù)據(jù):
insert student(sname,gender,class_id) values('鋼彈','女',1);
insert student(sname,gender,class_id) values('鐵錘','女',1);
insert student(sname,gender,class_id) values('山炮','男',2);
第三個表創(chuàng)建:
create table teacher(
tid int not null auto_increment primary key,
tname char(20) not null
)engine=innodb default charset=utf8;
插入數(shù)據(jù):
insert teacher(tname) values('波多');
insert teacher(tname) values('蒼空');
insert teacher(tname) values('飯島');
第四個表創(chuàng)建:
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);
插入數(shù)據(jù):
insert course(cname,tearch_id) values('生物',1);
insert course(cname,tearch_id) values('體育',1);
insert course(cname,tearch_id) values('物理',2);
第五個表創(chuàng)建:
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);
可能存在的問題:
假設(shè)第二句寫成:alter table score add constraint foreign key score(corse_id) references course(cid);
會報錯:ERROR 1061 (42000): Duplicate key name 'score'
原因是:外鍵名稱重復(fù),在key后面增加表名會默認(rèn)作為外鍵名,因此如果寫2條,就會出現(xiàn)外鍵名稱重復(fù)
解決辦法:刪除key后面的表名,mysql會默認(rèn)增加索引
插入數(shù)據(jù):
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);
總結(jié)
以上是生活随笔為你收集整理的mysql创建表格1warning_MySQLMySQL创建表及相关约束的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: golang goroutine实现_g
- 下一篇: linux cmake编译源码,linu