以创建学生教师表为例: 学生 id 关联教师 tid
学生表: student
教师表: teacher
sql语句 :
USE school;
CREATE TABLE student(
id INT(10) NOT NULL PRIMARY KEY,
NAME VARCHAR(30) DEFAULT NULL,
tid INT(10) DEFAULT NULL,
KEY `fktid` (`tid`),
CONSTRAINT `fktid` FOREIGN KEY(`tid`) REFERENCES `teacher` (`id`)
)ENGINE=INNODB DEFAULT CHARSET=utf8
INSERT INTO student VALUES(1,'小明',1);
INSERT INTO student VALUES(2,'小红',1);
INSERT INTO student VALUES(3,'小刚',1);
INSERT INTO student VALUES(4,'小王',1);
INSERT INTO student VALUES(5,'小智',1);
SELECT * FROM student;
CREATE TABLE teacher (
id INT(10) PRIMARY KEY NOT NULL,
NAME VARCHAR (30) DEFAULT NULL
)ENGINE=INNODB DEFAULT CHARSET=utf8
INSERT INTO teacher VALUES(1,'陈老师');
SELECT * FROM teacher;
重点: 外键关联语句,会手写才可以!
KEY `fktid` (`tid`),
CONSTRAINT `fktid` FOREIGN KEY(`tid`) REFERENCES `teacher` (`id`)
总结
到此这篇关于sql语句创建外键关联的文章就介绍到这了,更多相关sql创建外键关联内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!