如何在MySQL中通过auto_increment实时关联两个表?

时间:2018-06-28 20:43:28

标签: php mysql

我需要与他们的孩子实时创建某些行的副本。 我有两个真实的表,例如

create table order(
  id integer unsigned auto_increment
  , col_1 varchar(1)
  , col_2 varchar(1)
  # , ... lots of cols
  , primary key(id)
 )
# Relations between order and product
create table order_product(
  product_id integer unsigned
  , order_id integer unsigned
 )

原始行

select * from order;
id | col_1 | col_2
-------------------
1  | val_1 | val_2
select * from order_product;
product_id  | order_id
-----------------------
    15      |      1
    23      |      1

复制后的预期结果

select * from order;
id | col_1 | col_2
-------------------
1  | val_1 | val_2
2  | val_1 | val_2
select * from order_product;
product_id  | order_id
-----------------------
    15      |      1
    23      |      1
    15      |      2
    23      |      2

我创建了一个存储过程来执行类似的重复操作:

# Duplicate some orders
create temporary table tmp_order_dups like select * from order where 1=0;
insert into tmp_order_dups
select null id, col_1, col_2... from orders where <condition to duplicate>;

# Insert the duplicate orders in the real table
insert into order select * from tmp_order_dups;

# Now duplicate the products per order
create temporary table tmp_order_product_dups like 
select * from order_product where 1=0;
insert into tmp_order_prod_dups
select 
id_product
, '??' id_order # This should be the new autoincrement of my duplicate orders
from order_product
where id_order in(select id from orders where <condition to duplicate>);

关于仅使用sql(mysql)如何实现此目标的任何建议? 在php中,我会做一个for循环,并一一插入,最后插入的ID就像

$orders_to_dup = $con->query('select * from orders where <condition to duplicate>');
foreach($orders_to_dup as $order_to_dup){
  // Remove the id so it gets an autoincrement
   $old_order_id = $order_to_dup['id'];
   unset($order_to_dup['id']);  
  // The php framework returns the id of the inserted record using last_inserted_id()
  $new_order_id = $con->insert('order',$order_to_dup);
 // Get the products of the old order
   $products_to_dup = $con->query("select * from order_product where id_order = {$old_order_id}");
  // Put the products in the new order
  foreach($products_to_dup as $prod_to_dup){
     // Change the order_id
     $prod_to_dup['order_id'] = $new_order_id;
    // Duplicate the relation
    $con->insert('order_product', $prod_to_dup);
  }
}

0 个答案:

没有答案