Copy autoincrement value to another column on insert?

不想你离开。 提交于 2019-12-22 04:34:32

问题


Basically I have a table that versions products,

so it has two columns of interest, id | product_id

id is an autoincrement column,
product_id is just an int

When a product is first created the product_id comes from the id, When the product is edited we duplicate the row, so the product_id is the same, but the id is different. so when we first create the product we do two queries,

insert, then update table whatever set product_id = id where id = {the insert id}

This works, but I am wondering if there is a way to do it in one query?

Note we only have access to insert, update, delete. no triggers or stored procedures.


回答1:


Use the LAST_INSERT_ID() function:

update table whatever set
product_id = id
where id = last_insert_id()



回答2:


This is the single query:

insert into whatever 
set product_id = last_insert_id() + 1;


来源:https://stackoverflow.com/questions/13563419/copy-autoincrement-value-to-another-column-on-insert

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