从一个表插入另一个表(带有额外值)(MySQL)

时间:2014-04-14 13:57:19

标签: php mysql insert

进行了搜索但只能找到从一张桌子插入另一张桌子的东西。

我有这个查询从一个表中获取数据并将其插入到另一个表中:

INSERT INTO tbl_orders (product_id, customer_id) 
  SELECT product_id, customer_id FROM tbl_basket 
  WHERE customer_id = '" . $_SESSION['user'] . "'");

我想要做的是包含额外的数据。例如,我将根据另一个表插入product_id和customer_id,并插入不在另一个表中的额外值。

我试过这个没有运气:

INSERT INTO tbl_orders (product_id, customer_id, order_status) 
  SELECT product_id, customer_id, \'placed\' FROM tbl_basket 
  WHERE customer_id = '" . $_SESSION['user'] . "'"

有什么想法吗?谢谢。

1 个答案:

答案 0 :(得分:1)

如果要在表格中插入额外数据,可以尝试以下查询:

INSERT INTO tbl_orders (product_id, customer_id, order_status) 
SELECT product_id, customer_id, 'order_status' FROM tbl_basket 
WHERE customer_id = 'example'

如果第二个表中有额外的数据,您可以像这样加入第二个表:

INSERT INTO tbl_orders (product_id, customer_id, order_status) 
SELECT product_id, customer_id, t2.order_status FROM tbl_basket t1 
join tbl_basket2 t2 on t1.id = t2.id
WHERE t1.customer_id = 'example'