1

我正在创建一个名为 fac_master 的表,它有一个外键,它引用了 dept_master 的 dept_id。正在创建该表,但未在该表上强制执行外键。我在 dept_master 中也有一个外键,它工作得很好,但不适用于这个表。

create table Dept_Master
(   dept_id smallint unsigned auto_increment not null comment 'Department/Branch ID',
    dept_name varchar(100) not null comment 'Department Name such as Computer Engineering',
    prog_id tinyint unsigned not null comment 'Program ID under which this department falls',
    PRIMARY KEY(dept_id),
    CONSTRAINT fk_dept FOREIGN KEY(prog_id) REFERENCES Prog_Master(prog_id) ON DELETE RESTRICT ON UPDATE RESTRICT
) ENGINE=InnoDB COLLATE latin1_general_ci;


create table Fac_Master
(   fac_id smallint unsigned auto_increment not null comment 'Faculty ID',
    dept_id smallint unsigned not null comment 'Department Id of the department in which this faculty works',
    fac_name varchar(30) not null comment 'Name of the Faculty',
    fac_father_name varchar(30) comment 'Father\'s name of the faculty',
    fac_surname varchar(30) comment 'Surname of the faculty',
    fac_designation varchar(30) not null comment 'Designation of the faculty',
    fac_mail_id varchar(50) comment 'E-mail id of the faculty',
    fac_mobile bigint(10) unsigned comment 'Mobile number of the faculty',
    fac_address varchar(100) comment 'Permanent Address of the faculty',
    fac_status varchar(1) not null comment 'Status of Faculty: A=Active D=Deactive',
    fac_joining_date date comment 'Joining Date of the Faculty',
    PRIMARY KEY(fac_id),
    CONSTRAINT fk_faculty FOREIGN KEY(dept_id) REFERENCES Dept_Master(dept_id) ON DELETE RESTRICT ON UPDATE RESTRICT
) ENGINE=InnoDB COLLATE latin1_general_ci;

当我尝试在“dept_master”的“prog_id”中添加一个在“prog_master”的“prog_id”中不存在的值时,它会给出 fk 约束错误,这很好但是当我尝试在“dept_id”中添加一个值时“fac_master”在“dept_master”的“dept_id”中不存在,然后它被添加,但它应该给出一个 fk 约束错误。我还检查了信息模式中的外键约束,发现表 fac_master 没有外键约束。我在 Windows 7 HP 64 位版本上使用 WAMP Server 2.2。

问题是什么?请帮忙..

编辑:

alter table Fac_Master
add constraint fk_faculty FOREIGN KEY(dept_id) REFERENCES Dept_Master(dept_id) ON DELETE RESTRICT ON UPDATE RESTRICT;

如上所示使用alter table 有效,但与create table 一起使用时无效。可能是什么原因?

4

1 回答 1

3

看来问题是由您逃避'in的方式引起的'Father\'s name of the faculty'。当您更改它时'Father''s name of the faculty',您会发现外键约束已正确创建。

根据手册,包含单引号的两种方式都是正确的,因此这是一个错误。请参阅此 MySQL 错误票

于 2013-03-27T08:21:36.457 回答