1

我有下面的代码。事情是 SELECT LAST_INSERT_ID() 这总是返回最后插入的行。如果在获取最后一行之前实际插入了一行,我可以使用 INSERT IGNORE 进行检查,还是我简单地再次执行一个选择语句,即

SET _inserted_geolocation_id  =(SELECT id FROM geolocation where latitude= _geolocation_latitude AND longitude = _geolocation_longitude
    AND zoom = _geolocation_zoom AND yaw = _geolocation_yaw AND pitch =_geolocation_pitch);

BEGIN

DECLARE _inserted_geolocation_id int;

INSERT IGNORE INTO geolocation (latitude, longitude, zoom, yaw, pitch) 
VALUES (_geolocation_latitude, _geolocation_longitude, _geolocation_zoom, _geolocation_yaw, _geolocation_pitch);

/*SET _inserted_geolocation_id  = (SELECT LAST_INSERT_ID());*/
SET _inserted_geolocation_id  =(SELECT id FROM geolocation where latitude= _geolocation_latitude AND longitude = _geolocation_longitude
    AND zoom = _geolocation_zoom AND yaw = _geolocation_yaw AND pitch =_geolocation_pitch);

SELECT _inserted_geolocation_id;
END
4

1 回答 1

2

LAST_INSERT_ID()如果没有插入任何行,则返回 0 INSERT IGNORE,请参阅文档

如果您使用 INSERT IGNORE 并且该行被忽略,则 AUTO_INCREMENT 计数器不会增加并且 LAST_INSERT_ID() 返回 0,这反映了没有插入任何行。

于 2012-11-24T17:08:18.343 回答