外键是一种约束类型,可以用来维护表之间的完整性。如果我们为表创建外键,则该表称为子表,而第二个表称为父表。
在父表中,外键将充当主键。让我们创建一个表。
创建子表。
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);
以下是以下查询中上述语法的实现。
mysql> alter table StudentEnrollment add constraint StudCollegeConst foreign key(StudentFKPK) references College(StudentFKPK); Records: 0 Duplicates: 0 Warnings: 0
用于检查是否存在外键约束的语法。
SELECT TABLE_NAME, COLUMN_NAME,CONSTRAINT_NAME,REFERENCED_TABLE_NAME, REFERENCED_COLUMN_NA FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHER REFERENCED_TABLE_NAME = 'yourParentTableName or your referencedTableName';
上面的语法在下面的查询中实现。
mysql> SELECT -> TABLE_NAME, -> COLUMN_NAME, -> CONSTRAINT_NAME, -> REFERENCED_TABLE_NAME, -> REFERENCED_COLUMN_NAME -> FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE -> WHERE -> REFERENCED_TABLE_NAME = 'College';
这是输出。
+-------------------+-------------+------------------+-----------------------+------------------------+ | TABLE_NAME | COLUMN_NAME | CONSTRAINT_NAME | REFERENCED_TABLE_NAME | REFERENCED_COLUMN_NAME | +-------------------+-------------+------------------+-----------------------+------------------------+ | StudentEnrollment | StudentFKPK | StudCollegeConst | College | StudentFKPK | +-------------------+-------------+------------------+-----------------------+------------------------+ 1 row in set, 2 warnings (0.03 sec)
我们有一个名为StudentFKPK的列,而CONSTRAINT_NAME是StudCollegeConst。