<每日一题>题目15:mysql创建表及相关约束

 题目:

解答:

    第一个表创建:
        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('三年一班');
    第二个表创建:
    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);
   第三个表创建:
    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('饭岛');
   第四个表创建:
    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);     
    第五个表创建:
    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);

 

  

转载于:https://www.cnblogs.com/shuimohei/p/10259777.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值