Access Auto-Increment Value During INSERT INTO Statement

半城伤御伤魂 提交于 2019-11-27 08:38:36

问题


I am currently using MySQL. I have a table that has an auto_increment 'id' field, and an 'imgname' field containing a string that is the file name of an image.

I need to generate the 'imgname' value using the auto_increment value that is create by an INSERT INTO statement. The problem is, I don't know this value until I can use mysql_insert_id, AFTER the insert query has run. I would like to know if it's possible to access this value DURING the insert query somehow and then use it to generate my string in the query statement.

Thanks in advance.


回答1:


I would keep the id and imgname independent of each other and combine the two on SELECT when needed. If the need is frequent enough, create a view.




回答2:


Have a look at LAST_INSERT_ID() function. If performance is not an issue, INSERT regularly, and then UPDATE using LAST_INSERT_ID(), like:

UPDATE table SET name = CONCAT(name, "-", LAST_INSERT_ID()) WHERE id = LAST_INSERT_ID();


来源:https://stackoverflow.com/questions/6932339/access-auto-increment-value-during-insert-into-statement

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