MySQL使用其他表中的表的最后一个自动递增的ID

时间:2014-03-08 01:58:08

标签: javascript mysql sql

我目前有以下声明。

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());

我收到以下错误:

  

{[错误:ER_NO_REFERENCED_ROW_:无法添加或更新子行:外键约束失败(tripsdatabasetripstakentransportation,CONSTRAINT tripstakentransportation_ibfk_1 FOREIGN KEY(TripId)参考TripsTakenTripId))]     代码:'ER_NO_REFERENCED_ROW_',     错误:1452,     sqlState:'23000',     index:2}

只要语句INSERT INTO TripsTakenTransportation...出现两次,就会发生错误。我怀疑我的子查询(SELECT MAX(LAST_INSERT_ID()) FROM TripsTaken)没有按照我的预期进行第二次。

如何从表中获取LAST_INSERT_ID(),将其存储并在其他查询中重复使用?

注意:

Transportation也有一个自动增量列。

1 个答案:

答案 0 :(得分:2)

你赋予LAST_INSERT_ID()更多的智力。你不能说MAX(LAST_INSERT_ID()) FROM table,因为它没有绑定到表格。

这是你需要的东西:

INSERT INTO TripsTaken 
       (ProfileId, DestinationLocation, Name, 
        ImageUrl, StartDate, EndDate, Summary, Latitude, Longitude) 
VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?);

SET @tripsID := LAST_INSERT_ID();

INSERT INTO Transportation
       (Type, Location, StartDate, EndDate) 
VALUES (?, ?, ?, ?);

INSERT INTO TripsTakenTransportation 
       (TripId, id)
VALUES (@tripsID , LAST_INSERT_ID());

LAST_INSERT_ID()返回最近增加的自动增量列值的值。好消息是,对于与MySQL的每个不同连接,都有LAST_INSERT_ID()的值,因此您可以依赖它从SQL语句到连接中的语句是正确的。坏消息是你要非常小心,不要编辑你的SQL代码来添加新的INSERT语句,因为它们有改变LAST_INSERT_ID()的副作用。小心劈眼。