INSERT IGNORE INTO SELECT LAST_INSERT_ID()

时间:2012-11-24 15:56:46

标签: mysql

我有以下代码。事情是SELECT LAST_INSERT_ID()这总是返回最后插入的行。如果在获取最后一行之前实际插入了一行,或者我再次执行一个select语句,我可以使用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

1 个答案:

答案 0 :(得分:2)

如果LAST_INSERT_ID()未插入任何行,

INSERT IGNORE将返回0,请参阅Documentation

  

如果使用INSERT IGNORE并忽略该行,则为AUTO_INCREMENT   计数器没有递增,LAST_INSERT_ID()返回0,这   反映没有插入行。