This has me baffled, here's hoping someone can help.
Query:
insert into `shelter_pages` (`userid`,`relid`)
select :userid, `id` from `shelter` where `stage`='egg' order by rand() limit 30
Simple, right? Take 30 random rows meeting a condition, and save them in the "pages" table along with the user id.
The error:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`db_name`.`shelter_pages`, CONSTRAINT `shelter_pages_ibfk_2` FOREIGN KEY (`relid`) REFERENCES `shelter` (`id`) ON DELETE CASCADE ON UPDATE CASCADE)
Well how can that be? It's literally taking these `shelter`.`id`
values in the SELECT
query and INSERT
ing them, how can the foreign key check possibly fail?
If it's of any significance, the table in question is fairly "busy" - it is part of a gameplay element where any player can "adopt" from the shelter, thus deleting the row. Is this as simple as a race condition in what I thought would be an atomic operation?
shelter
table have data in that matches yourwhere
conditions? – Autochthoninsert..select
just inserts zero rows. – Sidranid
from..." or "select userid,id
from..." – Marivauxshelter
andshelter_pages
.. – Professionalizeshelter.id
is not nullable. – Sidraninsert..select
query? – Sidranselect into temporary structure, use temporary structure to insert final
then you can dumb temporary structure when it goes bad. Remember, it's for debug purpose, not something that should live for ever in a production environment :) – Perpendicularselect..insert
was in the hopes it would be reasonably atomic without locking the entire table. I realise that's idealistic, but I wonder... Wouldinsert ignore..select
work here, by having it drop the rows that fail the foreign key? – Sidraninsert into shelter_pages (userid,relid) select :userid, distinct(id) from shelter where stage='egg' order by rand() limit 30
– Wolfishselect
could be reading uncommitted data that would fail the foreign key constraints during theinsert
. It's a complete shot in the dark, but maybe worth checking. – PsychogenesisREAD UNCOMMITTED
), due to the stricter isolation levels causing huge deadlock problems. I've "fixed" it withINSERT IGNORE
but it's definitely something I need to keep in mind. Thank you! – Sidran