错误:无法添加或更新子行:外键约束 失败? (
testlogin
。leavetable
,约束leavetable_ibfk_1
外国钥匙
(users_id
)引用users
(id
)ON更新CASCADE上的DELCAD CASCADE)
在最后一天半收到此消息。试图在两个表之间建立一对多(外键)关系。在users:id
和leavetable:users_id
之间。当用户登录时,他们会获得一个id。当他们向专栏hours
提交表单时,我希望id能够保留表单数据。当有人创建新的ID号并且它不会更新leavetable:user_id
时,它会抛出错误。它抛出上面的错误。
这是我的代码:
CREATE TABLE IF NOT EXISTS `users` (
`email` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
`id` int(11) NOT NULL,
`password` char(64) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
`salt` char(16) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
`username` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE IF NOT EXISTS `leavetable` (
`hours` int(11) NOT NULL,
`users_id` int(11) DEFAULT NOT NULL,
`id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
ALTER TABLE `users`
ADD PRIMARY KEY (`id`) USING BTREE,
ADD UNIQUE KEY `email` (`email`) USING BTREE,
ADD UNIQUE KEY `username` (`username`) USING BTREE;
ALTER TABLE `leavetable`
ADD PRIMARY KEY (`id`) USING BTREE,
ADD KEY `users_id` (`users_id`) USING BTREE;
ALTER TABLE `leavetable`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
-- AUTO_INCREMENT for table `users`
ALTER TABLE `users`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
ALTER TABLE `leavetable`
ADD CONSTRAINT `leavetable_ibfk_1` FOREIGN KEY (`users_id`) REFERENCES
`users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
我的表结构:
+---------------------+
| Tables_in_testlogin |
+---------------------+
| leavetable |
| users |
+---------------------+
+----------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+--------------+------+-----+---------+----------------+
| email | varchar(255) | NO | UNI | NULL | |
| id | int(11) | NO | PRI | NULL | auto_increment |
| password | char(64) | NO | | NULL | |
| salt | char(16) | NO | | NULL | |
| username | varchar(255) | NO | UNI | NULL | |
+----------+--------------+------+-----+---------+----------------+
5 rows in set (0.01 sec)
+----------+---------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+---------+------+-----+---------+----------------+
| hours | int(11) | NO | | NULL | |
| users_id | int(11) | NO | MUL | NULL | |
| id | int(11) | NO | PRI | NULL | auto_increment |
+----------+---------+------+-----+---------+----------------+
3 rows in set (0.01 sec)
答案 0 :(得分:1)
首先,您必须清理子表的数据,然后在可以清除任何数据之后清除mastertable之间的外键