How to get the id of an inserted row ON insert?

↘锁芯ラ 提交于 2019-12-11 23:41:39

问题


I would like to create a unique hash of an AUTO-INCREMENT field while inserting that row. Something like:

INSERT INTO `table` (`hash`,`salt`) VALUES (MD5(CONCAT(`id`,`salt`)),'1234789687');

Is it possible to use the AUTO-INCREMENTED id of the row WHILE I'm inserting? Or do I have to wait until it's inserted to grab it via PHP or something?


回答1:


The short answer is no- it is not possible. If your db has low transaction volume, then concurrency may not be an issue to use something similar to select max() (susceptible to interference) : Can you access the auto increment value in MySQL within one statement?

I would follow the insert in php with an update

update `table`
set `hash` = MD5(CONCAT(`id`,`salt`))
where `id` = LAST_INSERT_ID();



回答2:


I don't know for sure, but really doubt that this is possible. I see why you would want to thought...It's not so elegant to insert the row, then immediately update it.

I would consider if you really need to store the hash in the DB or if you can calculate it during the select:

SELECT MD5(CONCAT(id,salt)) FROM table WHERE ...



来源:https://stackoverflow.com/questions/5465890/how-to-get-the-id-of-an-inserted-row-on-insert

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