InnoDB tables รองรับ foreign key constraints checking Foreign key constraint ไม่จำเป็นสำหรับ join 2 tables ใช้ได้ตอน define column สำหรับ storage engines อื่นนอกจาก InnoDB REFERENCES tableName(colName) ไม่มี effect จริง เป็นแค่ comment บอกว่า column นี้ intend to refer ไป column ใน table อื่น
MySQL ไม่ check ว่า 'colName' อยู่ใน 'tableName' จริง หรือ 'tableName' มีอยู่จริง
ใน parent table foreign key จะเป็น primary key ตัวอย่างสร้างตาราง:
สร้าง Child Table
mysql> create table StudentEnrollment
-> ( StudentId int,
StudentName varchar(200),
StudentFKPK int
-> ); Query OK, 0 rows affected (0.91 sec)
สร้าง Parent Table
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)
Parent table column 'StudentFKPK' เป็น primary key ใช้ ALTER command เพิ่ม foreign key
Syntax
ALTER table yourChildTableName add constraint anyConstraintName foreign key(primary key column name for parent table) references College(primary key column name for parent table);