10

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.

Hailwood
  • 89,623
  • 107
  • 270
  • 423

2 Answers2

2

Use the LAST_INSERT_ID() function:

update table whatever set
product_id = id
where id = last_insert_id()
Bohemian
  • 412,405
  • 93
  • 575
  • 722
0

This is the single query:

insert into whatever 
set product_id = last_insert_id() + 1;
tkocmathla
  • 901
  • 11
  • 24
  • 1
    There is no guarantee this will work if you have more than one table where you are inserting rows. – Erik S Aug 01 '16 at 13:06