Computer >> Máy Tính >  >> Lập trình >> MySQL

Cú pháp MySQL để tạo Khóa ngoại?

Cú pháp tạo khóa ngoại như sau -

alter table yourSecondTableName ADD CONSTRAINT yourConstraintname FOREIGN KEY(yourForeignKeyColumnName)
references yourFirstTableName (yourPrimaryKeyColumnName);

Để hiểu cú pháp trên, chúng ta hãy tạo hai bảng. Truy vấn để tạo bảng đầu tiên như sau -

mysql> create table Department_Table
   -> (
   -> Department_Id int not null auto_increment primary key,
   -> Department_Name varchar(30)
   -> );
Query OK, 0 rows affected (0.83 sec)

Truy vấn để tạo bảng thứ hai như sau -

mysql> create table Employee_Table
   -> (
   -> EmployeeID int not null auto_increment primary key,
   -> EmployeeName varchar(80),
   -> Job varchar(30),
   -> Department_Id int not null references department(departmentID)
   -> );
Query OK, 0 rows affected (1.12 sec)

Int Department_Id ở trên, không phải bộ phận tham chiếu null (DepartmentID) không tạo khóa ngoại. Bây giờ, hãy làm theo cú pháp trên để tạo khóa ngoại.

Truy vấn như sau -

mysql> alter table Employee_Table ADD CONSTRAINT fk_Department_Id FOREIGN KEY(Department_Id)
   -> references Department_Table(Department_Id);
Query OK, 0 rows affected (2.82 sec)
Records: 0 Duplicates: 0 Warnings: