
让我们了解一下如何在MySQL中使用外键 −
InnoDB表支持检查外键约束。不需要外键约束来连接两个表。它可以在定义需要使用的列时使用,用于除InnoDB之外的存储引擎。REFERENCES tableName(colName)没有实际效果,只是向用户注释当前正在定义的列意图引用不同表中的列。
MySQL不会检查确保'colName'实际上存在于'tableName'中,或者'tableName'本身是否真实存在。
在父表中,外键将充当主键。让我们看一个创建表的示例。
mysql> create table StudentEnrollment −> ( −> StudentId int, −> StudentName varchar(200), −> StudentFKPK int −> ); Query OK, 0 rows affected (0.91 sec)
mysql> create table College −> ( −> StudentFKPK int, −> CourseId int, −> CourseName varchar(200), −> CollegeName varchar(200), −> primary key(StudentFKPK) −> ); Query OK, 0 rows affected (0.46 sec)
在父表中,列 ‘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 中使用外键的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号