开发者

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

开发者 https://www.devze.com 2023-02-20 22:03 出处:网络
I would like to create a unique hash of an AUTO-INCREMENT field while inserting that row. Something like:

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开发者_开发知识库?


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();


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 ...

0

精彩评论

暂无评论...
验证码 换一张
取 消