在MySQL中使用外键
让我们了解如何在MySQL中使用外键-
InnoDB表支持检查外键约束。仅仅需要联接两个表就不需要外键约束。可以在定义需要使用的列时用于InnoDB之外的存储引擎。该参考tableName(colName)没有实际作用,并且向用户提供了一个注释,即当前定义的列旨在引用其他表中的列。
MySQL不会做任何检查来确保'colName'实际上存在于'tableName'中,或者确保'tableName'本身确实存在。
在父表中,外键将充当主键。让我们看一个创建表的例子。
创建子表
mysql> create table StudentEnrollment −> ( −> StudentId int, −> StudentName varchar(200), −> StudentFKPK int −> );
创建父表
mysql> create table College −> ( −> StudentFKPK int, −> CourseId int, −> CourseName varchar(200), −> CollegeName varchar(200), −> primary key(StudentFKPK) −> );
在父表中,“StudentFKPK”列是主键。我们将使用ALTER命令添加外键。
以下是添加外键的语法。
语法
ALTER table yourChildTableName add constraint anyConstraintName foreign key(primary key column name for parent table) references College(primary key column name for parent table);
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下