首页 / MYSQL / mysql 外键操作
mysql 外键操作
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了mysql 外键操作,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2185字,纯文字阅读大概需要4分钟。
内容图文
![mysql 外键操作](/upload/InfoBanner/zyjiaocheng/447/264dde2a9198487eaba8ee8bddc212a5.jpg)
/*主键唯一的不能为空null,一个表的主键只能由一个,可以有一个主键一个唯一uk间*/
/*primary key(sname,sid) 复合主键可以同时控制sname,sid用的比较少*/
/*外键fk一般都是2个表,只支持innodb引擎*/
drop table teacher;
create table teacher(
tid smallint unsigned not null auto_increment primary key,
tname varchar(10)
)engine=innodb charset utf8;
create table student(
sid int unsigned not null auto_increment primary key,
sname varchar(10),
stid smallint unsigned,
constraint fk foreign key (stid) references teacher(tid)
)engine=innodb charset utf8;
create table student(
sid int unsigned not null auto_increment primary key,
sname varchar(10),
stid smallint unsigned,
constraint fk foreign key (stid) references teacher(tid) on delete set null on update set null/*此种删除,只会删除老师,让学生的代课老师为空*/
)engine=innodb charset utf8;
create table student(
sid int unsigned not null auto_increment primary key,
sname varchar(10),
stid smallint unsigned,
constraint fk foreign key (stid) references teacher(tid) on delete set null/*此种删除,只会删除老师,让学生的代课老师为空*/
)engine=innodb charset utf8;
drop table student;
create table student(
sid int unsigned not null auto_increment primary key,
sname varchar(10),
stid smallint unsigned,
constraint fk foreign key (stid) references teacher(tid) on delete cascade/*级联删除,删除老师的同时,把学生也删除了*/
)engine=innodb charset utf8;
insert into teacher values(null,‘李老师‘);
insert into teacher values(null,‘王老师‘);
insert into teacher values(null,‘陈老师‘);
insert into teacher values(null,‘名老师‘);
select * from teacher;
select database();
use xx;
insert into student values(null,‘李四‘,4);
insert into student values(null,‘小明‘,8);
insert into student values(null,‘李‘,7);
insert into student values(null,‘小‘,6);
select * from student;
/*删除老师1,1老师有代课下面的学生表所以不能删除,没带课的可以删除*/
delete from teacher where tid=2;
delete from teacher where tid=7;
/*因为是学生表里面有外键控制所以删除的时候先删除学生表再删除老师表*/
drop table student;
mysql 外键操作
标签:
本文系统来源:http://www.cnblogs.com/lsr111/p/4462531.html
内容总结
以上是互联网集市为您收集整理的mysql 外键操作全部内容,希望文章能够帮你解决mysql 外键操作所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。