sql語句創建外鍵關聯的完整實例
以創建學生教師表為例: 學生 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創建外鍵關聯內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!