Php 将数据从一个表插入到另一个表-MySQL

Php 将数据从一个表插入到另一个表-MySQL,php,mysql,Php,Mysql,所以我想做一个小的网上商店。我有两张表:cart\u products和order\u products。在这些表中,有两种类型的项目可以添加到购物车中:促销和产品。这两种类型的项目存储在不同的表中,称为:促销和产品 最初,所有产品/促销都会添加到购物车表中,一旦用户签出,它们就会转移到订单表中,并从购物车表中删除 如果所选项目是产品,则默认情况下,promotion\u id值设置为0。反之亦然,如果所选项目是促销活动。这是我的基本结构: cart\u产品 ------------------

所以我想做一个小的网上商店。我有两张表:
cart\u products
order\u products
。在这些表中,有两种类型的项目可以添加到购物车中:
促销
产品
。这两种类型的项目存储在不同的表中,称为:
促销
产品

最初,所有产品/促销都会添加到
购物车
表中,一旦用户签出,它们就会转移到
订单
表中,并从
购物车
表中删除

如果所选项目是产品,则默认情况下,
promotion\u id
值设置为
0
。反之亦然,如果所选项目是促销活动。这是我的基本结构:

cart\u产品

----------------------------------------------------------------------------------
| cart_products_id |    cart_id    |   product_id | promotion_id      | quantity |
----------------------------------------------------------------------------------
| 6                |       1       |   5          | 0                 | 2  
---------------------------------------------------------------------------------
订购产品

----------------------------------------------------------------------------------
| cart_products_id |    cart_id    |   product_id | promotion_id      | quantity |
----------------------------------------------------------------------------------
| 6                |       1       |   5          | 0                 | 2  
---------------------------------------------------------------------------------

我遇到的问题是试图
左键加入
产品/促销,以获取所选项目的
价格。这是我目前的疑问

INSERT INTO order_details (order_id, user_id, product_id, promotion_id, price, quantity)
VALUES(
  '6', 
  '7',
  (SELECT 
    cart_products.product_id, 
    cart_products.promotion_id,
    IF(cart_products.promotion_id = '0', products.price, promotions.price),
    cart_products.quantity

  FROM cart_products


  LEFT JOIN products
  ON cart_products.product_id = products.product_id

  LEFT JOIN promotions
  cart_products.promotion_id = promotions.promotion_id

  WHERE cart_products.cart_id = '6')
)

但是,这会给我一个错误
非唯一表/别名
。有人知道我该怎么做吗?非常感谢您的帮助

您不必像以前那样定义值,只需选择常量,即可使用INSERT INTO select语法:

INSERT INTO order_details (order_id, user_id, product_id, promotion_id, price, quantity)
SELECT (
    '6', 
    '7',
    cart_products.product_id, 
    cart_products.promotion_id,
    IF(cart_products.promotion_id = '0', products.price, promotions.price),
    cart_products.quantity
  FROM cart_products
  LEFT JOIN products
    ON cart_products.product_id = products.product_id
  LEFT JOIN promotions
    ON cart_products.promotion_id = promotions.promotion_id
  WHERE cart_products.cart_id = '6'
)

另外,我相信您在第二次左连接时忘记了一个“ON”子句

谢谢,我最后不得不将
SELECT
放在括号内,这样它才能工作,否则它会给我一个错误。但我成功了。