7

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 INSERTing 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?

4

1 回答 1

1

这很可能发生,因为您将事务隔离级别设置为“脏读”(即READ UNCOMMITTED)。这意味着SELECT可能正在读取未提交的数据,这些数据在INSERT.

于 2016-07-03T14:33:03.530 回答