2013-03-27 80 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