我想我可能错误地创建了一个约束。我有三个表:活动,身份验证,登录。我希望身份验证成为“主要”表,我将插入数据以创建用户,以及他的详细信息。它将与新创建的表(存储会话ID的身份验证)具有一对一的关系(在身份验证中登录到id
中id
)。第三个表与AuthenticationID
的多行具有一对多关系,对应于登录的id
。
这就是我创造的:
| Login | CREATE TABLE `Login` (
`id` int(6) unsigned NOT NULL AUTO_INCREMENT,
`TimeLoggedIn` text NOT NULL,
`sessionid` varchar(255) NOT NULL,
PRIMARY KEY (`id`),
KEY `id` (`id`),
KEY `id_2` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=latin1 |
| Authentication | CREATE TABLE `Authentication` (
`id` int(6) unsigned NOT NULL AUTO_INCREMENT,
`userid` varchar(30) NOT NULL,
`password` varchar(30) NOT NULL,
`role` varchar(20) NOT NULL,
`email` varchar(50) DEFAULT NULL,
`AuthenticationID` int(6) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
CONSTRAINT `Authentication_ibfk_1` FOREIGN KEY (`id`) REFERENCES `Login` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=latin1 |
| Activity | CREATE TABLE `Activity` (
`num` int(11) NOT NULL AUTO_INCREMENT,
`AuthenticationID` int(6) unsigned NOT NULL,
`TorrentMag` mediumtext NOT NULL,
PRIMARY KEY (`num`),
KEY `FK_myKey2` (`AuthenticationID`),
CONSTRAINT `FK_myKey` FOREIGN KEY (`AuthenticationID`) REFERENCES `Authentication` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `FK_myKey2` FOREIGN KEY (`AuthenticationID`) REFERENCES `Authentication` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=104 DEFAULT CHARSET=latin1 |
不幸的是,当我尝试在Authentication中插入一个新行时(在我创建约束之前一直工作),
INSERT INTO Authentication (userid, password, role, email) VALUES ("user", "SeG^SU;B2_&Uhw", "user", "someone@mydomain.com");
它给出了错误:
Cannot add or update a child row: a foreign key constraint fails (`episodescopy`.`Authentication`, CONSTRAINT `Authentication_ibfk_1` FOREIGN KEY (`id`) REFERENCES `Login` (`id`))
所以我无意中创造了我需要的反向关系?另外我似乎在表Activity上创建了一个重复约束?我怎样才能解决这个问题?
答案 0 :(得分:1)
这是一个建议,希望至少能指出你正确的方向。如果要在Authentication
表中创建用户,则应将引用Authentication
主键的任何其他表列(即id
)声明为外键引用。< / p>
CREATE TABLE Login (
id int(6) unsigned NOT NULL AUTO_INCREMENT,
TimeLoggedIn text NOT NULL,
sessionid varchar(255) NOT NULL,
PRIMARY KEY (id),
KEY id (id),
KEY id_2 (id),
CONSTRAINT fk_1 FOREIGN KEY (id) REFERENCES Authentication (id)
) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=latin1
CREATE TABLE Authentication (
id int(6) unsigned NOT NULL AUTO_INCREMENT,
userid varchar(30) NOT NULL,
password varchar(30) NOT NULL,
role varchar(20) NOT NULL,
email varchar(50) DEFAULT NULL,
AuthenticationID int(6) unsigned DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=latin1
您当前的设置正好相反,要求用户在Login
中存在,然后才能将其插入Authentication
。