2013-03-27 82 views
1

我正在创建一个名为fac_master的表,它具有一个指向dept_master的dept_id的外键。该表正在创建,但外键在该表上未得到执行。我在dept_master中也有一个外键,它工作得很好,但不适合这个表格。MySQL:在InnoDB中被忽略的外键约束

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_master”“prog_id”的“prog_id”添加一个值,那么它给FK约束错误这是很好的,但是当我尝试添加在“dept_master”的“dept_id”中不存在的“fac_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如上图所示的作品,但与创建表时没有。这可能是什么原因呢?

+0

你可以添加'SHOW CREATE TABLE Fac_Master;'的输出吗? – 2013-03-27 08:14:44

回答

3

看起来问题是由于您在'Father\'s name of the faculty'中跳过'的方式造成的。当您在'Father''s name of the faculty'中更改它时,您会发现正确创建了外键约束。

根据手册,包含单引号的两种方法都是正确的,所以它是一个错误。见this MySQL bug ticket

+0

哇。很好的发现。坚持标准SQL并且不使用非标准怪癖的另一个好理由...... – 2013-03-27 08:54:08