2012-11-24 182 views
1

我有下面的代碼。事情是用SELECT LAST_INSERT_ID()這總是返回最後插入的行。我可以用INSERT檢查ignore如果連續漸漸最後一行時實際插入或我簡單做一個select語句再次即INSERT IGNORE INTO 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); 

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 

回答

2

LAST_INSERT_ID()返回0,如果沒有行被INSERT IGNORE插,見Documentation

如果使用INSERT忽略和行被忽略,則AUTO_INCREMENT 計數器不增加和LAST_INSERT_ID()返回0,這 反映沒有行插入。

+0

SET _inserted_geolocation_id =(SELECT LAST_INSERT_ID());即使當我添加重複行時,也返回最後一行 –

+0

INSERT IGNORE INTO geolocation(緯度,經度,縮放,偏航,俯仰)VALUES(_geolocation_latitude,_geolocation_longitude,_geolocation_zoom,_geolocation_yaw,_geolocation_pitch); SELECT LAST_INSERT_ID(); –