我在将数据插入表格时遇到问题。我已经多次重新创建了这两个表,试图解决我的问题。第一个表login,包含id(主键),用户名和密码。第二个表userinfo包含id(主键),名字,姓氏,电子邮件和登录$ id(引用登录主键ID的外键)。我可以很好地插入登录表,我总是首先插入,以便第二个表可以获得第一个表的id用作外键。但是一旦我将数据插入userinfo表,我就得到了 错误1452:无法添加或更新子行:外键constaint失败。 我不知道为什么它一直无法插入。任何帮助都会很好,谢谢你。
+-------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+------------------+------+-----+---------+----------------+
| id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| user | varchar(50) | NO | | NULL | |
| passwd| varchar(50) | NO | | NULL | |
+-------+------------------+------+-----+---------+----------------+
+-------------------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------------+------------------+------+-----+---------+----------------+
| id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| firstN | varchar(50) | NO | | NULL | |
| lastN | varchar(50) | NO | | NULL | |
| email | varchar(125) | NO | | NULL | |
| login$id | int(10) unsigned | NO | MUL | NULL | |
+-------------------+------------------+------+-----+---------+----------------+
这是我的表格代码
CREATE TABLE login(
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
user VARCHAR(50) NOT NULL,
passwd VARCHAR(50) NOT NULL,
PRIMARY KEY (id)
);
CREATE TABLE userinfo(
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
firstN VARCHAR(50) NOT NULL,
lastN VARCHAR(50) NOT NULL,
email VARCHAR(125) NOT NULL,
login$id INT UNSIGNED NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (login$id) REFERENCES login(id)
);
答案 0 :(得分:2)
This is because INSERT
query for userinfo
table does not have login id. You can get the last inserted id for login
by using LAST_INSERT_ID()
MySQL function and amend the queries like below:
INSERT INTO login (user, passwd) VALUES ('DDan', 'Password1');
INSERT INTO userinfo (firstN, lastN, email, login$id) VALUES ('Dan', 'Dan', 'email@yahoo.com', LAST_INSERT_ID());
Here's the SQL Fiddle, and here's the documentation for LAST_INSERT_ID().