I am working on a django based project which created two tables table1
and table2
with a foreign key from table2
to table1
. I need to insert some values manually into table2
. On trying to do so in MySQL I get the constraint failure error. I checked thoroughly, corresponding entries required for a foreign key constraint already exist in table1
. I looked into some previous questions on SO but could not find an appropriate solution.
Table1 Schema:
+------------+---------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+---------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| email | varchar(100) | NO | | NULL | |
Table 2:
+-------------+---------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+---------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| km | varchar(1000) | YES | | NULL | |
| owner_id | int(11) | NO | MUL | NULL | |
| receiver_id | int(11) | NO | MUL | NULL | |
+-------------+---------------+------+-----+---------+----------------+
The insert statement insert into crest_recipient values(id,owner_id=5,receiver_id=5,km="hello world");
or similar ones fail with the exact error as
Cannot add or update a child row: a foreign key constraint fails (crest.crest_recipient CONSTRAINT crest_recipient_owner_id_4943116a1387be04_fk_crest_user_id FOREIGN KEY (owner_id) REFERENCES crest_user (id))
You are trying to insert a row in child table crest_recipient which does not exist in parent table crest_user.
So first insert corresponding row in master table then you can insert in child table.
You are attempting to update or insert a row in crest.crest_recipient
table, a value in column owner_id
that does not exist in crest_user
column id
make it look like this
insert crest_recipient (km,owner_id,receiver_id) values ('test',5,1)
'test',5,1
are whatever you want.
Skip the id column. Don't specify it, don't supply the value for it. It is an auto_increment PK most likely (basically there is nothing else it can be). The db engine chooses it for you. Specifying it will just screw things up 99% of the time.
Focus on parameter 2 for now (the 5)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.