2013-04-13 104 views
1

我知道這已被要求allot,並且我很抱歉,但我真的找不到答案。無法創建表(errno:150)

這是我的管理員表:

CREATE TABLE `admins` (
    `admin_id` int(11) NOT NULL AUTO_INCREMENT, 
    `admin_user` varchar(15) NOT NULL, 
    `admin_password` varchar(15) NOT NULL, 
    `admin_fName` varchar(20) NOT NULL, 
    `admin_lName` varchar(20) NOT NULL, 
    PRIMARY KEY (`admin_id`) 
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1 

,我試圖創建引用admin_fname表:

CREATE TABLE IF NOT EXISTS posts(
    post_id INT NOT NULL AUTO_INCREMENT, 
     post_title varchar(50), 
     post_content varchar(255), 
     post_user varchar(20) NOT NULL, 
     PRIMARY KEY (post_id), 
     FOREIGN KEY (post_user) REFERENCES admins(admin_fName) 
) ENGINE = INNODB; 

post_user似乎有相同的屬性admin_fname,且有父表中的數據。請問任何機構請解釋這裏發生的事情?

回答

2

您不能在表admins的列admin_fname上參考post_user,因爲您沒有在其上定義關鍵字。要直接回答你的問題,你必須在列上添加一個關鍵,

CREATE TABLE `admins` 
(
    `admin_id` int(11) NOT NULL AUTO_INCREMENT, 
    `admin_user` varchar(15) NOT NULL, 
    `admin_password` varchar(15) NOT NULL, 
    `admin_fName` varchar(20) NOT NULL, 
    `admin_lName` varchar(20) NOT NULL, 
    KEY (admin_fName),      -- <<== adding key 
    PRIMARY KEY (`admin_id`) 
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1 

但不要引用到NON_UNIQUE列一個好主意,因爲從長遠來看記錄可以混合具有相同fname用戶。更好的設計是離開桌子。在表posts上添加一個引用其主鍵的列。

CREATE TABLE `admins` 
(
    `admin_id` int(11) NOT NULL AUTO_INCREMENT, 
    `admin_user` varchar(15) NOT NULL, 
    `admin_password` varchar(15) NOT NULL, 
    `admin_fName` varchar(20) NOT NULL, 
    `admin_lName` varchar(20) NOT NULL, 
    PRIMARY KEY (`admin_id`) 
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1; 

CREATE TABLE IF NOT EXISTS posts 
(
     post_id INT NOT NULL AUTO_INCREMENT, 
     post_title varchar(50), 
     post_content varchar(255), 
     admin_id int(11) NOT NULL, 
     PRIMARY KEY (post_id), 
     FOREIGN KEY (admin_id) REFERENCES admins(admin_id) 
) ENGINE = INNODB; 
+0

啊,謝謝你,覺得很愚蠢的遺忘:我 – ReallyGoodPie

+0

看到我更新的答案。 ':D'希望你明白我的觀點.. –

+0

謝謝,非常感謝:) – ReallyGoodPie

相關問題