无法创建表(错误号:150)

时间:2013-04-13 07:45:29

标签: mysql sql database-design foreign-keys

我知道这已经被问过了,我很抱歉,但老实说我找不到答案。

这是我的管理员表:

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具有相同的属性,并且父表中有数据。请问任何人可以解释这里发生的事情吗?

1 个答案:

答案 0 :(得分:2)

由于您没有在其上定义密钥,因此无法在表post_user上的admin_fname列上引用admins。要直接回答您的问题,您必须在列上添加一个键,

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;