日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 运维知识 > 数据库 >内容正文

数据库

mysql创建表格1warning_MySQLMySQL创建表及相关约束

發(fā)布時間:2025/4/16 数据库 21 豆豆
生活随笔 收集整理的這篇文章主要介紹了 mysql创建表格1warning_MySQLMySQL创建表及相关约束 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

第一個表創(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)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。