mysql 外來鍵sql語言編寫

2021-09-23 10:43:45 字數 804 閱讀 6888

先建立乙個班級表

create table c_class(id int(5) primary key auto_increment,name varchar(10));

建立好後向裡面新增資料

insert into c_class values(0,『python1』),(0,『python2』);

再建立乙個學生表 將學生表的外來鍵加到班級表的主鍵中

create table t_student(id int primary key auto_increment,name varchar(10),gender enum(『男』,『女』),c_id int(5) ,foreign key(c_id) references c_class(id));

向學生表新增資料

#新增的c_id不能超過c_class的範圍

inset into t_student (0,『tom』,『男』,1),(0,『jack』,『女』,2);

刪除外來鍵

先檢視外鍵名

show create table t_student;

alter table t_student drop foreign key 外鍵名;

新增外鍵名

alter table t_student add foreign key(c_id) references c_class(id);

檢視是否加入外來鍵

show create table t_student;

sql外來鍵需要輸入嗎 SQL外來鍵

在本教程中,將學習sql外來鍵以及如何建立foreign key約束以強制表之間的關係。1.sql外來鍵約束簡介 外來鍵是一列或一組列,用於強制兩個表中的資料之間的鏈結。在外鍵引用中,第乙個表的主鍵列 或多個列 由第二個表的列 或列 引用。第二個表的列 或列 成為外來鍵。在建立或更改表時,可以使用f...

mysql 外來鍵 del 記錄 MySQL 外來鍵

在mysql中 1 mysql 資料表主要支援六種型別 分別是 bdb heap isam merge myisam innobdb。這六種又分為兩類,一類是 事務安全型 transaction safe 包括bdb和innodb 其餘都屬於第二類,稱為 非事務安全型 non transaction...

SQL建立外來鍵

建立外來鍵關係 先建主表再見從表 主表 create table zhu code int primary key name varchar 20 從表 create table cong code int primary key name varchar 20 zhu int,foreign ke...