MySQL:在InnoDB中忽略外键约束

时间:2013-03-27 05:06:35

标签: mysql sql foreign-keys

我正在创建一个名为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“of”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一起使用时则不行。可能是什么原因?

1 个答案:

答案 0 :(得分:3)

问题似乎是您逃离' 'Father\'s name of the faculty'的方式造成的。在'Father''s name of the faculty'中更改它时,您会发现正确创建了外键约束。

根据手册,包含单引号的两种方式都是正确的,所以这是一个错误。请参阅this MySQL bug ticket