且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

创建外键的MySQL语法

更新时间:2022-11-08 18:40:57

MySQL接受它(不抱怨关于语法),但实际上并没有创建外键。

要创建这个外键,运行这个命令:

  ALTER TABLE雇员ADD CONSTRAINT fk_department FOREIGN KEY(departmentID)REFERENCES department(departmentID); 


Is this syntax correct in creating a Foreign Key?

create table department
(
  departmentID int not null auto_increment primary key,
  name varchar(30)
) type=InnoDB;

create table employee
(
  employeeID int not null auto_increment primary key,
  name varchar(80),
  job varchar(30),
  departmentID int not null references department(departmentID)
) type=InnoDB;

It looks like MySQL accepts it (doesn't complain about the syntax) but the foreign key is not actually created.

To create this foreign key, run this command:

ALTER TABLE employee ADD CONSTRAINT fk_department FOREIGN KEY (departmentID) REFERENCES department (departmentID);