1
Error: Cannot add or update a child row: a foreign key constraint fails? (
testlogin
.leavetable
, CONSTRAINTleavetable_ibfk_1
FOREIGN KEY
(users_id
) REFERENCESusers
(id
) ON DELETE CASCADE ON UPDATE CASCADE)錯誤:無法添加或更新子行:外鍵約束失敗?
在最後一天半的時間裏得到這條消息。試圖在兩個表之間建立一對多(外鍵)關係。在users:id
和leavetable:users_id
之間。當用戶登錄時,他們會得到一個ID。當他們將表格提交給hours
列時,我希望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)
如果它位於更新標記或插入位置,並且FK就位,則該操作違反FK約束。 '用戶'中不存在'leavetable.user_id' – Drew
如何在新用戶註冊時更新它。我剛剛改變了一點。它被命名爲'leavetable.id',但沒關係。 –
你能否僅僅向我們展示兩個表的最終結果,'show create table users'和'show create table leavetable' – Drew