我知道这已经被问过了,我很抱歉,但老实说我找不到答案。
这是我的管理员表:
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具有相同的属性,并且父表中有数据。请问任何人可以解释这里发生的事情吗?
答案 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;