I currently have the following statements.
INSERT INTO TripsTaken (ProfileId, DestinationLocation, Name, ImageUrl, StartDate, EndDate, Summary, Latitude, Longitude) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?);
INSERT INTO Transportation(Type, Location, StartDate, EndDate) VALUES (?, ?, ?, ?);
INSERT INTO TripsTakenTransportation (TripId, id) VALUES( (SELECT MAX(LAST_INSERT_ID()) FROM TripsTaken) , LAST_INSERT_ID());
INSERT INTO Transportation(Type, Location, StartDate, EndDate) VALUES (?, ?, ?, ?);
INSERT INTO TripsTakenTransportation (TripId, id) VALUES( (SELECT MAX(LAST_INSERT_ID()) FROM TripsTaken) , LAST_INSERT_ID());
I'm getting the following error:
{ [Error: ER_NO_REFERENCED_ROW_: Cannot add or update a child row: a foreign key constraint fails (
tripsdatabase
.tripstakentransportation
, CONSTRAINTtripstakentransportation_ibfk_1
FOREIGN KEY (TripId
) REFERENCESTripsTaken
(TripId
))] code: 'ER_NO_REFERENCED_ROW_', errno: 1452, sqlState: '23000', index: 2 }
The error occurs whenever the statement INSERT INTO TripsTakenTransportation...
occurs twice. I suspect my sub query (SELECT MAX(LAST_INSERT_ID()) FROM TripsTaken)
is not doing what I expected the second time around.
How can I get the LAST_INSERT_ID() from a table, store it and reuse it in my other queries?
Note:
Transportation
also has an auto increment column.