last_insert_id() vs SELECT Max(ID)

让人想犯罪 __ 提交于 2019-12-02 02:13:52

问题


Is using SELECT Max(ID) FROM table safer than using SELECT last_insert_id(), where they run as 2 separate queries?

I'm concerned that before the last_insert_id() can run, another insert will take place.


回答1:


Is using SELECT Max(ID) FROM table safer than using SELECT last_insert_id()

Definitely not, never! LAST_INSERT_ID() exists exactly for the reason you state: Other clients could have made other inserts. LAST_INSERT_ID() always gives you the last inserted ID on the current connection.

mySQL Reference




回答2:


Using select max(id) is just asking for trouble. It's only a matter of time before two inserts would happen near-simultaneously and you would start to see some craziness in your data.



来源:https://stackoverflow.com/questions/3180510/last-insert-id-vs-select-maxid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!